// ---- BRAISE — shared components ---------------------------------------
const { useState, useEffect, useRef } = React;

// ---- Tiny inline icons (stroke) ---------------------------------------
function Icon({ name, size = 18, stroke = 1.6, style }) {
  const common = { width: size, height: size, viewBox: "0 0 24 24", fill: "none",
    stroke: "currentColor", strokeWidth: stroke, strokeLinecap: "round", strokeLinejoin: "round", style };
  switch (name) {
    case "flame": return <svg {...common}><path d="M12 3c0 3-4 4-4 8a4 4 0 0 0 8 0c0-2-1-3-2-4 0 1.5-1 2-1 2s1-3-1-6Z"/></svg>;
    case "arrow-right": return <svg {...common}><path d="M5 12h14M13 6l6 6-6 6"/></svg>;
    case "arrow-left": return <svg {...common}><path d="M19 12H5M11 6l-6 6 6 6"/></svg>;
    case "calendar": return <svg {...common}><rect x="3" y="5" width="18" height="16" rx="2"/><path d="M3 9h18M8 3v4M16 3v4"/></svg>;
    case "clock": return <svg {...common}><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 2"/></svg>;
    case "users": return <svg {...common}><circle cx="9" cy="8" r="3"/><path d="M3 20c0-3 3-5 6-5s6 2 6 5"/><path d="M16 5.5a3 3 0 0 1 0 5M21 20c0-2.3-1.6-4-4-4.6"/></svg>;
    case "sun": return <svg {...common}><circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4 12H2M22 12h-2M5 5l1.5 1.5M17.5 17.5 19 19M19 5l-1.5 1.5M6.5 17.5 5 19"/></svg>;
    case "moon": return <svg {...common}><path d="M20 13A8 8 0 1 1 11 4a6 6 0 0 0 9 9Z"/></svg>;
    case "check": return <svg {...common}><path d="M5 12l5 5L20 6"/></svg>;
    case "phone": return <svg {...common}><path d="M5 4h4l1.5 5-2 1.5a11 11 0 0 0 5 5l1.5-2 5 1.5v4a2 2 0 0 1-2 2A16 16 0 0 1 3 6a2 2 0 0 1 2-2Z"/></svg>;
    case "pin": return <svg {...common}><path d="M12 21s7-6 7-11a7 7 0 0 0-14 0c0 5 7 11 7 11Z"/><circle cx="12" cy="10" r="2.5"/></svg>;
    case "minus": return <svg {...common}><path d="M5 12h14"/></svg>;
    case "plus": return <svg {...common}><path d="M12 5v14M5 12h14"/></svg>;
    case "spark": return <svg {...common}><path d="M12 3v6M12 15v6M3 12h6M15 12h6"/></svg>;
    case "lock": return <svg {...common}><rect x="4" y="10" width="16" height="11" rx="2"/><path d="M8 10V7a4 4 0 0 1 8 0v3"/></svg>;
    case "leaf": return <svg {...common}><path d="M4 20c0-9 7-15 16-15 0 9-7 15-16 15Z"/><path d="M4 20c4-6 8-8 12-9"/></svg>;
    default: return null;
  }
}

// ---- Logo -------------------------------------------------------------
function Logo({ onClick, light }) {
  return (
    <button onClick={onClick} style={{ display: "flex", alignItems: "center", gap: 10, background: "none", padding: 0 }}>
      <span style={{
        width: 30, height: 30, borderRadius: "50%", display: "grid", placeItems: "center",
        background: "var(--ember)", color: "var(--paper)", flexShrink: 0,
      }}>
        <Icon name="flame" size={17} stroke={1.8} />
      </span>
      <span style={{
        fontFamily: "var(--font-display)", fontSize: 23, letterSpacing: "0.14em",
        color: light ? "var(--bone)" : "var(--ink)",
      }}>BRAISE</span>
    </button>
  );
}

// ---- Placeholder image ------------------------------------------------
function Ph({ label, tone = "", style, className = "" }) {
  const toneCls = tone ? ` ph--${tone}` : "";
  return (
    <div className={`ph${toneCls} ${className}`} style={style}>
      {label && <span className="ph__label">{label}</span>}
    </div>
  );
}

// ---- Header -----------------------------------------------------------
function Header({ route, go, light }) {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 20);
    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  const onDark = light && !scrolled;
  const links = [
    ["Maison", "home"],
    ["Mes réservations", "mes-resas"],
  ];
  return (
    <header style={{
      position: "sticky", top: 0, zIndex: 50,
      background: onDark ? "transparent" : "color-mix(in oklch, var(--bone) 86%, transparent)",
      backdropFilter: onDark ? "none" : "saturate(1.4) blur(12px)",
      borderBottom: `1px solid ${onDark ? "transparent" : "var(--line-soft)"}`,
      transition: "all 0.4s var(--ease)",
    }}>
      <div className="container" style={{ height: 74, display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <Logo onClick={() => go("home")} light={onDark} />
        <nav style={{ display: "flex", alignItems: "center", gap: 32 }}>
          {links.map(([label, r]) => (
            <button key={r} onClick={() => go(r)} className="hide-mobile" style={{
              fontSize: 13.5, fontWeight: 500, letterSpacing: "0.02em",
              color: onDark ? "var(--bone)" : (route === r ? "var(--ink)" : "var(--ink-soft)"),
              opacity: route === r ? 1 : 0.78,
              borderBottom: route === r ? "1px solid currentColor" : "1px solid transparent",
              paddingBottom: 2,
            }}>{label}</button>
          ))}
          <button className={`btn ${onDark ? "" : "btn--ember"}`} onClick={() => go("reserver")}
            style={onDark ? { background: "var(--bone)", borderColor: "var(--bone)", color: "var(--ink)", padding: "12px 22px", fontSize: 12.5 } : { padding: "12px 22px", fontSize: 12.5 }}>
            Réserver
          </button>
        </nav>
      </div>
    </header>
  );
}

// ---- Footer -----------------------------------------------------------
function Footer({ go }) {
  return (
    <footer style={{ background: "var(--espresso)", color: "var(--bone)", marginTop: "auto" }}>
      <div className="container" style={{ padding: "64px 32px 40px" }}>
        <div className="foot-grid" style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr 1fr", gap: 48, alignItems: "start" }}>
          <div>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 18 }}>
              <span style={{ width: 28, height: 28, borderRadius: "50%", display: "grid", placeItems: "center", background: "var(--ember)", color: "var(--paper)" }}>
                <Icon name="flame" size={16} stroke={1.8} />
              </span>
              <span style={{ fontFamily: "var(--font-display)", fontSize: 22, letterSpacing: "0.14em" }}>BRAISE</span>
            </div>
            <p style={{ margin: 0, maxWidth: 320, color: "color-mix(in oklch, var(--bone) 72%, transparent)", fontSize: 14.5, lineHeight: 1.7 }}>
              {RESTO.baseline}. {RESTO.intro}
            </p>
          </div>
          <div>
            <div className="eyebrow eyebrow--light" style={{ marginBottom: 16 }}>Le lieu</div>
            <p style={{ margin: 0, fontSize: 14.5, lineHeight: 1.9, color: "color-mix(in oklch, var(--bone) 80%, transparent)" }}>
              {RESTO.address}<br />{RESTO.phone}<br />{RESTO.email}
            </p>
          </div>
          <div>
            <div className="eyebrow eyebrow--light" style={{ marginBottom: 16 }}>Service</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 10, alignItems: "flex-start" }}>
              <button onClick={() => go("reserver")} className="link-underline">Réserver une table</button>
              <button onClick={() => go("mes-resas")} className="link-underline">Mes réservations</button>
              <button onClick={() => go("home")} className="link-underline">Le menu</button>
            </div>
          </div>
        </div>
        <div style={{ marginTop: 48, paddingTop: 24, borderTop: "1px solid oklch(0.32 0.02 45)", display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 12, fontSize: 12.5, color: "color-mix(in oklch, var(--bone) 60%, transparent)" }}>
          <span>© {new Date().getFullYear()} BRAISE — Maison de cuisine au feu de bois</span>
          <span style={{ display: "flex", gap: 20 }}>
            <span>Mentions légales</span><span>Confidentialité</span>
          </span>
        </div>
      </div>
    </footer>
  );
}

// ---- Party stepper ----------------------------------------------------
function PartyStepper({ value, onChange, min = 1, max = 12 }) {
  const btn = (dir, disabled) => (
    <button disabled={disabled} onClick={() => onChange(Math.min(max, Math.max(min, value + dir)))}
      style={{
        width: 42, height: 42, borderRadius: "50%", border: "1px solid var(--line)",
        background: "var(--paper)", display: "grid", placeItems: "center",
        color: disabled ? "var(--line)" : "var(--ink)", transition: "all 0.2s var(--ease)",
        cursor: disabled ? "not-allowed" : "pointer",
      }}>
      <Icon name={dir > 0 ? "plus" : "minus"} size={16} />
    </button>
  );
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 18 }}>
      {btn(-1, value <= min)}
      <div style={{ minWidth: 90, textAlign: "center" }}>
        <div style={{ fontFamily: "var(--font-display)", fontSize: 34, lineHeight: 1 }}>{value}</div>
        <div style={{ fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--ink-faint)", marginTop: 4 }}>
          {value === 1 ? "couvert" : "couverts"}
        </div>
      </div>
      {btn(1, value >= max)}
    </div>
  );
}

// ---- Calendar ---------------------------------------------------------
function Calendar({ value, onChange }) {
  const today = new Date(); today.setHours(0, 0, 0, 0);
  const [view, setView] = useState(() => { const d = value ? fromISO(value) : new Date(); return new Date(d.getFullYear(), d.getMonth(), 1); });

  const year = view.getFullYear(), month = view.getMonth();
  const firstDow = (new Date(year, month, 1).getDay() + 6) % 7; // Mon=0
  const daysInMonth = new Date(year, month + 1, 0).getDate();
  const cells = [];
  for (let i = 0; i < firstDow; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) cells.push(new Date(year, month, d));

  const maxDate = new Date(); maxDate.setDate(maxDate.getDate() + 60);
  const canPrev = new Date(year, month, 1) > new Date(today.getFullYear(), today.getMonth(), 1);

  return (
    <div style={{ background: "var(--paper)", border: "1px solid var(--line)", borderRadius: "var(--radius-lg)", padding: 22 }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 18 }}>
        <button onClick={() => canPrev && setView(new Date(year, month - 1, 1))} disabled={!canPrev}
          style={{ width: 34, height: 34, borderRadius: "50%", border: "1px solid var(--line)", color: canPrev ? "var(--ink)" : "var(--line)", display: "grid", placeItems: "center", cursor: canPrev ? "pointer" : "not-allowed" }}>
          <Icon name="arrow-left" size={15} />
        </button>
        <div style={{ fontFamily: "var(--font-display)", fontSize: 19, letterSpacing: "0.02em" }}>{MOIS[month]} {year}</div>
        <button onClick={() => setView(new Date(year, month + 1, 1))}
          style={{ width: 34, height: 34, borderRadius: "50%", border: "1px solid var(--line)", color: "var(--ink)", display: "grid", placeItems: "center" }}>
          <Icon name="arrow-right" size={15} />
        </button>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(7,1fr)", gap: 4, marginBottom: 6 }}>
        {["L", "M", "M", "J", "V", "S", "D"].map((d, i) => (
          <div key={i} style={{ textAlign: "center", fontSize: 11, fontWeight: 600, color: "var(--ink-faint)", letterSpacing: "0.06em", padding: "4px 0" }}>{d}</div>
        ))}
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(7,1fr)", gap: 4 }}>
        {cells.map((d, i) => {
          if (!d) return <div key={i} />;
          const iso = toISO(d);
          const past = d < today;
          const tooFar = d > maxDate;
          const closed = isClosed(d);
          const disabled = past || tooFar || closed;
          const selected = value === iso;
          const isToday = iso === toISO(today);
          return (
            <button key={i} disabled={disabled} onClick={() => onChange(iso)}
              title={closed ? "Fermé le lundi" : ""}
              style={{
                aspectRatio: "1", borderRadius: 10, border: selected ? "1px solid var(--ember)" : "1px solid transparent",
                background: selected ? "var(--ember)" : (disabled ? "transparent" : "var(--bone)"),
                color: selected ? "var(--paper)" : (disabled ? "var(--line)" : "var(--ink)"),
                fontSize: 14, fontWeight: selected ? 600 : 400,
                cursor: disabled ? "not-allowed" : "pointer",
                textDecoration: closed && !past ? "line-through" : "none",
                position: "relative", transition: "all 0.18s var(--ease)",
              }}>
              {d.getDate()}
              {isToday && !selected && <span style={{ position: "absolute", bottom: 6, left: "50%", transform: "translateX(-50%)", width: 4, height: 4, borderRadius: "50%", background: "var(--ember)" }} />}
            </button>
          );
        })}
      </div>
    </div>
  );
}

// ---- Reusable section heading ----------------------------------------
function SectionHead({ eyebrow, title, sub, align = "left", light }) {
  return (
    <div style={{ textAlign: align, maxWidth: align === "center" ? 620 : "none", margin: align === "center" ? "0 auto" : 0 }}>
      {eyebrow && <div className={`eyebrow ${light ? "eyebrow--light" : ""}`} style={{ marginBottom: 16 }}>{eyebrow}</div>}
      <h2 style={{ fontSize: "clamp(28px, 4vw, 44px)", color: light ? "var(--bone)" : "var(--ink)" }}>{title}</h2>
      {sub && <p style={{ marginTop: 16, fontSize: 16, lineHeight: 1.7, color: light ? "color-mix(in oklch, var(--bone) 74%, transparent)" : "var(--ink-soft)" }}>{sub}</p>}
    </div>
  );
}

Object.assign(window, { Icon, Logo, Ph, Header, Footer, PartyStepper, Calendar, SectionHead });
