// 內 UCHI web — member app shell + Home + Vantagens + Eventos + Account + modals

const NAV_LINKS = [
  { id: "home", t: "Início" },
  { id: "reserve", t: "Reservas" },
  { id: "events", t: "Eventos" },
  { id: "benefits", t: "Pertencer" },
  { id: "order", t: "Pedidos" },
  { id: "chat", t: "Concierge" },
];

function MemberApp({ onSignOut }) {
  const D = window.UCHI;
  const [page, setPage] = React.useState("home");
  const [modal, setModal] = React.useState(null);
  const go = (p) => { setPage(p); window.scrollTo({ top: 0 }); };

  return (
    <div>
      <Nav active={page} onNav={go} links={NAV_LINKS} member={D.member} onSignOut={onSignOut}
        onAccount={(m) => m === "card" ? setModal({ type: "card" }) : go("account")} />

      <main key={page} className="fade">
        {page === "home" && <Home D={D} go={go} open={setModal} />}
        {page === "reserve" && <Reserve D={D} />}
        {page === "order" && <Order D={D} />}
        {page === "benefits" && <Benefits D={D} open={setModal} />}
        {page === "events" && <Events D={D} open={setModal} />}
        {page === "chat" && <Chat D={D} />}
        {page === "account" && <Account D={D} go={go} open={setModal} onSignOut={onSignOut} />}
        {page === "billing" && <Billing D={D} go={go} />}
      </main>

      <Footer D={D} />

      {modal?.type === "card" && <CardModal D={D} onClose={() => setModal(null)} />}
      {modal?.type === "benefit" && <BenefitModal b={modal.data} onClose={() => setModal(null)} />}
      {modal?.type === "event" && <EventModal e={modal.data} onClose={() => setModal(null)} />}
    </div>
  );
}

function Page({ children, style }) {
  return <div className="container" style={{ padding: "clamp(36px,5vw,64px) 28px 90px", ...style }}>{children}</div>;
}

// ───────────────────────── Home ─────────────────────────
function Home({ D, go, open }) {
  const m = D.member;
  return (
    <Page>
      {/* hero */}
      <div className="home-hero" style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 40, alignItems: "center", marginBottom: 64 }}>
        <div>
          <Eyebrow accent style={{ marginBottom: 14 }}>Bem-vindo a casa</Eyebrow>
          <h1 className="display" style={{ fontSize: "clamp(38px,5vw,64px)" }}>{m.name.split(" ")[0]}.</h1>
          <div style={{ display: "flex", alignItems: "center", gap: 10, margin: "20px 0 18px" }}>
            <span className="rule" style={{ width: 32 }} />
            <FounderTag m={m} />
          </div>
          <p className="body-lg" style={{ maxWidth: 460 }}>{m.standing} A mesa do canto fica à tua espera, e a casa guarda-te dois bancos ao balcão esta sexta.</p>
          <div style={{ display: "flex", gap: 12, marginTop: 30, flexWrap: "wrap" }}>
            <Button variant="primary" onClick={() => go("reserve")} icon="arrowR">Reservar</Button>
            <Button variant="ghost" onClick={() => go("chat")}>Falar com a casa</Button>
          </div>
        </div>
        <MemberCard m={m} onClick={() => open({ type: "card" })} />
      </div>

      {/* tonight */}
      <SectionHead eyebrow="Esta noite" title="O que te espera"
        action={<button className="linkbtn" onClick={() => go("reserve")} style={linkBtn}>Ver reservas</button>} />
      <Card hover onClick={() => go("reserve")} style={{ padding: 0, overflow: "hidden", display: "grid", gridTemplateColumns: "minmax(220px,300px) 1fr", marginBottom: 64 }} className="tonight-card">
        <Photo ground="lantern" height="100%" label="balcão · brasa" style={{ minHeight: 200 }} />
        <div style={{ padding: 30, display: "flex", flexDirection: "column", justifyContent: "center" }}>
          <Tag tone="accent" style={{ alignSelf: "flex-start", marginBottom: 16 }}>Sexta · 20:30</Tag>
          <h2 className="h2">Balcão do chef</h2>
          <p className="body" style={{ margin: "10px 0 22px", maxWidth: 420 }}>Dois bancos guardados. Omakase — sem ementa, o chef decide por ti. Traz o teu +1.</p>
          <div style={{ display: "flex", gap: 12 }}>
            <Button variant="accent" onClick={(e) => { e.stopPropagation(); go("reserve"); }}>Ver reserva</Button>
            <Button variant="ghost" onClick={(e) => { e.stopPropagation(); go("chat"); }}>Avisar a casa</Button>
          </div>
        </div>
      </Card>

      {/* quick links */}
      <div className="quick-grid" style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 16, marginBottom: 64 }}>
        <Quick icon="calendar" t="Reservar" s="balcão ou mesa" onClick={() => go("reserve")} />
        <Quick icon="bowl" t="Pedir" s="antes de chegar" onClick={() => go("order")} />
        <Quick icon="bottle" t="A tua garrafa" s={D.bottles.length + " guardadas"} onClick={() => go("order")} />
        <Quick icon="message" t="Concierge" s="fala com a Mariko" onClick={() => go("chat")} />
      </div>

      {/* events */}
      <SectionHead eyebrow="Noites fechadas" title="O que há a chegar"
        action={<button onClick={() => go("events")} style={linkBtn}>Ver todos</button>} />
      <div className="events-grid" style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 18 }}>
        {D.events.slice(0, 3).map(e => <EventCard key={e.id} e={e} onClick={() => open({ type: "event", data: e })} />)}
      </div>
    </Page>
  );
}

const linkBtn = { background: "none", border: "none", cursor: "pointer", color: "var(--accent)", fontFamily: "inherit", fontSize: 14, fontWeight: 700, whiteSpace: "nowrap" };

function Quick({ icon, t, s, onClick }) {
  return (
    <button onClick={onClick} className="card hover" style={{ padding: 22, textAlign: "left", cursor: "pointer",
      display: "flex", flexDirection: "column", gap: 16, fontFamily: "inherit", background: "var(--surface)" }}>
      <Icon name={icon} size={24} style={{ color: "var(--accent)" }} />
      <div><div className="h3" style={{ fontSize: 16 }}>{t}</div><div className="cap" style={{ marginTop: 4 }}>{s}</div></div>
    </button>
  );
}

function EventCard({ e, onClick }) {
  return (
    <div className="card hover" onClick={onClick} style={{ padding: 0, overflow: "hidden", cursor: "pointer" }}>
      <Photo ground={e.ground} height={150}>
        <div style={{ position: "absolute", left: 16, top: 14, color: "var(--ink)" }}>
          <div style={{ fontWeight: 900, fontSize: 22, lineHeight: 1 }}>{e.date.split(" ")[0]}</div>
          <div className="cap" style={{ letterSpacing: ".16em", color: "var(--ink-2)" }}>{e.date.split(" ")[1]}</div>
        </div>
        <div style={{ position: "absolute", right: 12, top: 12 }}><AccessBadge item={e} style={{ background: "rgba(20,12,8,0.55)", backdropFilter: "blur(6px)", color: "#E9D4A8", borderColor: "rgba(233,212,168,0.5)" }} /></div>
      </Photo>
      <div style={{ padding: 20 }}>
        <h3 className="h3">{e.t}</h3>
        <p className="cap" style={{ marginTop: 6, lineHeight: 1.45 }}>{e.sub}</p>
        <div style={{ marginTop: 14, display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
          <Tag tone={e.spots.includes("espera") ? "dim" : "accent"}>{e.price ? e.price : e.spots}</Tag>
          {e.price && <span className="cap">{e.spots}</span>}
          {e.until && <span className="cap">· {e.until}</span>}
        </div>
      </div>
    </div>
  );
}

// early-access state badge — "members first, public only if seats remain"
function AccessBadge({ item, style }) {
  const a = item.access;
  if (a === "members-first") return <Tag tone="accent" style={style}>Membros primeiro</Tag>;
  if (a === "members-only") return <Tag tone="accent" style={style}>Só membros</Tag>;
  if (a === "waitlist") return <Tag tone="dim" style={style}>Lista de espera</Tag>;
  return null;
}

// ───────────────────────── Membership card (always dark lacquer) ─────────────────────────
// quiet founder mark — "from the start"
function FounderTag({ m }) {
  if (!m.founder) return null;
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 8, fontSize: 11, fontWeight: 700,
      letterSpacing: ".18em", textTransform: "uppercase", color: "var(--accent)" }}>
      <Brush size={15} color="var(--accent)" />Membro fundador · {m.seat}
    </span>
  );
}

function MemberCard({ m, onClick, big }) {
  return (
    <div onClick={onClick} style={{ position: "relative", overflow: "hidden", cursor: onClick ? "pointer" : "default",
      borderRadius: 8, padding: big ? 34 : 28, aspectRatio: big ? "auto" : "1.586",
      background: "#6B2A20",
      backgroundImage: "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='160' height='160'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.72' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E\")",
      backgroundBlendMode: "overlay", border: "1px solid rgba(201,168,120,0.4)",
      boxShadow: "0 16px 40px rgba(46,18,13,0.4)", color: "#F4E8D2" }}>
      <div style={{ position: "absolute", fontWeight: 900, fontSize: big ? 280 : 200, lineHeight: 1, top: big ? -50 : -36, right: -24,
        color: "rgba(244,232,210,0.07)", pointerEvents: "none" }}>縁</div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", position: "relative" }}>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 9 }}>
          <Brush size={big ? 32 : 26} color="#E9D4A8" /><span style={{ fontWeight: 900, fontSize: big ? 17 : 14, letterSpacing: ".2em" }}>EN&nbsp;HOUSE</span>
        </span>
        <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: ".16em", textTransform: "uppercase", padding: "5px 11px",
          borderRadius: 999, color: "#E9D4A8", border: "1px solid rgba(233,212,168,0.55)" }}>{m.tier}</span>
      </div>
      <div style={{ marginTop: big ? 60 : 44, position: "relative" }}>
        <div style={{ fontSize: 11, letterSpacing: ".22em", color: "rgba(244,232,210,0.6)", fontWeight: 700, marginBottom: 6 }}>{m.founder ? "MEMBRO FUNDADOR" : "MEMBRO"}</div>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end" }}>
          <div>
            <div style={{ fontWeight: 800, fontSize: big ? 24 : 20, letterSpacing: "-0.01em" }}>{m.name}</div>
            <div style={{ fontSize: 12, color: "rgba(244,232,210,0.6)", marginTop: 4 }}>{m.since}</div>
          </div>
          <div style={{ textAlign: "right" }}>
            <div style={{ fontSize: 9.5, letterSpacing: ".2em", color: "rgba(244,232,210,0.5)", fontWeight: 700, marginBottom: 3 }}>LUGAR</div>
            <div style={{ fontWeight: 900, fontSize: big ? 22 : 18, letterSpacing: ".04em", color: "#E9D4A8" }}>{m.seat || m.no}</div>
          </div>
        </div>
      </div>
    </div>
  );
}

function FauxQR({ size = 168 }) {
  const cells = 21, pat = [];
  for (let y = 0; y < cells; y++) for (let x = 0; x < cells; x++) {
    const corner = (x < 7 && y < 7) || (x > cells - 8 && y < 7) || (x < 7 && y > cells - 8);
    pat.push(corner ? (x === 0 || x === 6 || y === 0 || y === 6 || (x > 1 && x < 5 && y > 1 && y < 5) ||
      (x > cells - 8 && (x === cells - 7 || x === cells - 1 || (x > cells - 6 && x < cells - 2 && y > 1 && y < 5))) ||
      (y > cells - 8 && (y === cells - 7 || y === cells - 1 || (y > cells - 6 && y < cells - 2 && x > 1 && x < 5))))
      : ((x * 7 + y * 13 + x * y) % 5 < 2));
  }
  return <div style={{ width: size, height: size, display: "grid", gridTemplateColumns: `repeat(${cells},1fr)`, background: "#140c08", padding: 10, borderRadius: 6 }}>
    {pat.map((on, i) => <div key={i} style={{ background: on ? "#EAE0CE" : "transparent" }} />)}</div>;
}

// ───────────────────────── Vantagens ─────────────────────────
function Benefits({ D, open }) {
  return (
    <Page>
      <SectionHead eyebrow="Pertencer" title="O que é ser de dentro." sub="Não é uma lista de descontos. É uma casa que te conhece — e guarda um lugar com o teu nome." />
      <div className="ben-grid" style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 18 }}>
        {D.benefits.map(b => (
          <div key={b.k} className="card hover" onClick={() => open({ type: "benefit", data: b })} style={{ padding: 0, overflow: "hidden", cursor: "pointer" }}>
            <Photo ground={b.ground} height={160} />
            <div style={{ padding: 24 }}>
              <h3 className="h3">{b.t}</h3>
              <p className="small" style={{ marginTop: 8 }}>{b.d}</p>
            </div>
          </div>
        ))}
      </div>
    </Page>
  );
}

// ───────────────────────── Eventos ─────────────────────────
function Events({ D, open }) {
  const [view, setView] = React.useState("tudo");
  const showNoites = view === "tudo" || view === "noites";
  const showProvas = view === "tudo" || view === "provas";
  return (
    <Page>
      <SectionHead eyebrow="Só para dentro" title="Eventos & provas."
        sub="Noites fechadas e provas guiadas. Os membros entram primeiro — ao público só sobra o que não enchermos."
        action={
          <div className="seg">
            <button className={view === "tudo" ? "on" : ""} onClick={() => setView("tudo")}>Tudo</button>
            <button className={view === "noites" ? "on" : ""} onClick={() => setView("noites")}>Noites</button>
            <button className={view === "provas" ? "on" : ""} onClick={() => setView("provas")}>Provas</button>
          </div>} />
      {showNoites && (
        <div style={{ marginBottom: view === "tudo" ? 48 : 0 }}>
          {view === "tudo" && <Eyebrow accent style={{ marginBottom: 16, display: "block" }}>Noites fechadas</Eyebrow>}
          <div className="events-grid" style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 18 }}>
            {D.events.map(e => <EventCard key={e.id} e={e} onClick={() => open({ type: "event", data: e })} />)}
          </div>
        </div>
      )}
      {showProvas && (
        <div>
          {view === "tudo" && <Eyebrow accent style={{ marginBottom: 16, display: "block" }}>Provas & experiências</Eyebrow>}
          <div className="events-grid" style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 18 }}>
            {D.provas.map(p => <EventCard key={p.id} e={p} onClick={() => open({ type: "event", data: p })} />)}
          </div>
        </div>
      )}
    </Page>
  );
}

// ───────────────────────── Account ─────────────────────────
function Account({ D, go, open, onSignOut }) {
  const m = D.member;
  return (
    <Page style={{ maxWidth: 720 }}>
      <SectionHead eyebrow="A tua conta" title="Conta & preferências." />
      <div style={{ marginBottom: 32 }}><MemberCard m={m} onClick={() => open({ type: "card" })} /></div>
      <div className="card" style={{ padding: "4px 22px" }}>
        <AccRow icon="user" t="Perfil" s={m.name + " · " + m.tier} />
        <AccRow icon="users" t="Convidados" s="2 por visita · este mês usaste 1" />
        <AccRow icon="card" t="Adesão & pagamentos" s="Fundador · 500€/ano · renova jan. 2027" onClick={() => go("billing")} />
        <AccRow icon="bell" t="Notificações" s="barris novos, noites fechadas" />
        <AccRow icon="qr" t="O meu cartão" s="mostra à porta" onClick={() => open({ type: "card" })} last />
      </div>
      <div style={{ marginTop: 24 }}><Button variant="ghost" onClick={onSignOut} icon="logout">Terminar sessão</Button></div>
    </Page>
  );
}
function AccRow({ icon, t, s, onClick, last }) {
  return (
    <button onClick={onClick} style={{ width: "100%", display: "flex", alignItems: "center", gap: 16, padding: "18px 0",
      background: "none", border: "none", cursor: onClick ? "pointer" : "default", textAlign: "left",
      borderBottom: last ? "none" : "1px solid var(--line)", fontFamily: "inherit" }}>
      <div style={{ width: 40, height: 40, borderRadius: 999, flexShrink: 0, background: "color-mix(in srgb, var(--accent) 10%, transparent)",
        border: "1px solid var(--line)", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--accent)" }}><Icon name={icon} size={18} /></div>
      <div style={{ flex: 1 }}><div className="h3" style={{ fontSize: 16 }}>{t}</div><div className="cap" style={{ marginTop: 3 }}>{s}</div></div>
      <Icon name="chevR" size={16} style={{ color: "var(--ink-3)" }} />
    </button>
  );
}

// ───────────────────────── Modals ─────────────────────────
function CardModal({ D, onClose }) {
  const m = D.member;
  return (
    <Modal onClose={onClose}>
      <div style={{ padding: 30 }}>
        <Eyebrow accent style={{ marginBottom: 20 }}>O teu cartão</Eyebrow>
        <MemberCard m={m} big />
        <div style={{ textAlign: "center", marginTop: 24 }}>
          <div style={{ display: "inline-block", padding: 16, background: "var(--bg-2)", borderRadius: 8, border: "1px solid var(--line)" }}><FauxQR size={172} /></div>
          <p className="small" style={{ marginTop: 16 }}>Mostra à porta, ou ao balcão. Abre-te a sala.</p>
          <p className="cap" style={{ marginTop: 6, letterSpacing: ".18em" }}>{m.no} · {m.tier.toUpperCase()}</p>
        </div>
      </div>
    </Modal>
  );
}

function BenefitModal({ b, onClose }) {
  return (
    <Modal onClose={onClose} wide>
      <Photo ground={b.ground} height={240} radius={0}>
        <div style={{ position: "absolute", inset: 0, background: "linear-gradient(180deg, transparent, var(--surface))" }} />
      </Photo>
      <div style={{ padding: "0 36px 40px", marginTop: -40, position: "relative" }}>
        <Eyebrow accent>Ser de dentro</Eyebrow>
        <h2 className="h1" style={{ margin: "12px 0 0" }}>{b.t}</h2>
        <div className="rule" style={{ margin: "20px 0" }} />
        <p className="body-lg">{b.d}</p>
        <p className="body" style={{ marginTop: 16 }}>Faz parte de seres de dentro. Não precisas de pedir — a casa já sabe. Chega, senta-te, deixa-te levar.</p>
      </div>
    </Modal>
  );
}

function EventModal({ e, onClose }) {
  const [rsvp, setRsvp] = React.useState(false);
  const prova = e.kind === "prova";
  const wait = e.access === "waitlist" || e.spots.includes("espera");
  return (
    <Modal onClose={onClose} wide>
      <Photo ground={e.ground} height={260} radius={0}>
        <div style={{ position: "absolute", inset: 0, background: "linear-gradient(180deg, transparent 40%, var(--surface))" }} />
        <div style={{ position: "absolute", left: 36, bottom: 30, display: "flex", gap: 8 }}>
          <Tag tone="accent" style={{ background: "var(--surface)" }}>{e.dow} · {e.date}</Tag>
          <AccessBadge item={e} style={{ background: "var(--surface)" }} />
        </div>
      </Photo>
      <div style={{ padding: "0 36px 36px", marginTop: -10, position: "relative" }}>
        <Eyebrow accent>{prova ? "Prova guiada" : "Noite fechada"}</Eyebrow>
        <h2 className="h1" style={{ margin: "12px 0 0" }}>{e.t}</h2>
        <div className="rule" style={{ margin: "20px 0" }} />
        <p className="body-lg">{e.sub}.</p>
        {e.access === "members-first"
          ? <p className="body" style={{ marginTop: 14 }}>Os membros reservam primeiro{e.until ? ` — ${e.until}` : ""}. Só abrimos ao público se sobrarem lugares.</p>
          : <p className="body" style={{ marginTop: 14 }}>Só para dentro. Lugares contados — a sala fecha quando enche. Traz quem souber estar à mesa.</p>}
        <div style={{ display: "flex", gap: 28, margin: "26px 0 30px", flexWrap: "wrap" }}>
          <div><div className="cap">Lugares</div><div className="h3" style={{ marginTop: 4 }}>{e.spots}</div></div>
          <div style={{ width: 1, background: "var(--line)" }} />
          {prova
            ? <React.Fragment>
                <div><div className="cap">Com</div><div className="h3" style={{ marginTop: 4 }}>{e.host}</div></div>
                <div style={{ width: 1, background: "var(--line)" }} />
                <div><div className="cap">Por pessoa</div><div className="h3" style={{ marginTop: 4 }}>{e.price}</div></div>
              </React.Fragment>
            : <div><div className="cap">Convidados</div><div className="h3" style={{ marginTop: 4 }}>até 2</div></div>}
        </div>
        <Button variant={rsvp ? "ghost" : "primary"} onClick={() => setRsvp(true)} icon={rsvp ? "check" : "arrowR"}>
          {rsvp ? (wait ? "Estás na lista de espera" : "Lugar guardado") : (wait ? "Entrar na lista de espera" : (prova ? "Reservar lugar na prova" : "Guardar o meu lugar"))}
        </Button>
      </div>
    </Modal>
  );
}

function Footer({ D }) {
  return (
    <footer style={{ borderTop: "1px solid var(--line)", marginTop: 40 }}>
      <div className="container" style={{ padding: "40px 28px", display: "flex", justifyContent: "space-between", alignItems: "center", gap: 20, flexWrap: "wrap" }}>
        <Wordmark size={14} mark={20} />
        <span className="cap">{D.club.gloss}</span>
        <span className="cap">© EN House</span>
      </div>
    </footer>
  );
}

Object.assign(window, { MemberApp, NAV_LINKS, Page, Home, Quick, EventCard, MemberCard, FauxQR, Benefits, Events, Account, AccRow, CardModal, BenefitModal, EventModal, Footer, linkBtn });
