// 內 UCHI web — member part 2: Reserve, Order, Chat

// ───────────────────────── Reservas ─────────────────────────
function Reserve({ D }) {
  const [mode, setMode] = React.useState("table");
  return (
    <Page>
      <SectionHead eyebrow="A tua mesa" title="Reservas"
        sub={mode === "private" ? "A casa, ou um canto dela, só vossa. Desenhamos a noite convosco." : null}
        action={
          <div className="seg">
            <button className={mode === "table" ? "on" : ""} onClick={() => setMode("table")}>Mesa</button>
            <button className={mode === "private" ? "on" : ""} onClick={() => setMode("private")}>Espaço privado</button>
            <button className={mode === "up" ? "on" : ""} onClick={() => setMode("up")}>Próximas</button>
          </div>} />
      {mode === "table" && <TableReserve D={D} />}
      {mode === "private" && <PrivateReserve D={D} />}
      {mode === "up" && (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill,minmax(300px,1fr))", gap: 18 }}>
          <BookingCard date="Sex 6 jun · 20:30" t="Mesa do chef" s="2 pessoas · omakase" tag="Confirmada" />
          <BookingCard date="Qui 19 jun · 21:00" t="Takeover — chef Aoki" s="2 pessoas · 8 tempos" tag="Lista de espera" dim />
          <BookingCard date="Sáb 12 jul · 13:00" t="Almoço de negócios — Sala privada" s="14 pessoas · proposta enviada" tag="Em proposta" dim />
        </div>
      )}
    </Page>
  );
}

// ---- regular table ----
function TableReserve({ D }) {
  const [venue, setVenue] = React.useState("chef");
  const [day, setDay] = React.useState(1);
  const [time, setTime] = React.useState("20:30");
  const [size, setSize] = React.useState(2);
  const [done, setDone] = React.useState(false);
  const days = [{ d: "Qui", n: "5" }, { d: "Sex", n: "6" }, { d: "Sáb", n: "7" }, { d: "Dom", n: "8" }, { d: "Seg", n: "9" }, { d: "Ter", n: "10" }, { d: "Qua", n: "11" }];
  const times = ["18:30", "19:00", "20:00", "20:30", "21:30", "22:30"];
  const v = D.venues.find(x => x.id === venue);
  if (done) return <ReserveDone D={D} v={v} day={days[day]} time={time} size={size} onAgain={() => setDone(false)} />;

  return (
    <div className="reserve-grid" style={{ display: "grid", gridTemplateColumns: "1fr 360px", gap: 40, alignItems: "start" }}>
      <div>
        <Eyebrow accent style={{ marginBottom: 16 }}>Onde te sentas</Eyebrow>
        <div style={{ display: "grid", gap: 12, marginBottom: 38 }}>
          {D.venues.map(x => {
            const on = venue === x.id;
            return (
              <button key={x.id} onClick={() => setVenue(x.id)} className="card" style={{ padding: 20, cursor: "pointer", textAlign: "left",
                fontFamily: "inherit", border: "1px solid " + (on ? "var(--accent)" : "var(--line)"), background: on ? "var(--surface-2)" : "var(--surface)",
                display: "flex", alignItems: "center", gap: 16 }}>
                <div style={{ flex: 1 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                    <span className="h3" style={{ fontSize: 17 }}>{x.t}</span>{x.note && <Tag tone={on ? "accent" : "dim"}>{x.note}</Tag>}
                  </div>
                  <div className="cap" style={{ marginTop: 5 }}>{x.sub}</div>
                </div>
                <div style={{ width: 22, height: 22, borderRadius: 999, flexShrink: 0, border: "2px solid " + (on ? "var(--accent)" : "var(--line-2)"),
                  background: on ? "var(--accent)" : "transparent", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--on-accent)" }}>
                  {on && <Icon name="check" size={13} stroke={2.4} />}</div>
              </button>
            );
          })}
        </div>

        <Eyebrow accent style={{ marginBottom: 16 }}>Que dia</Eyebrow>
        <div style={{ display: "flex", gap: 10, flexWrap: "wrap", marginBottom: 38 }}>
          {days.map((d, k) => {
            const on = day === k;
            return (
              <button key={k} onClick={() => setDay(k)} style={{ width: 64, padding: "13px 0", borderRadius: 4, cursor: "pointer",
                fontFamily: "inherit", textAlign: "center", border: "1px solid " + (on ? "var(--accent)" : "var(--line-2)"),
                background: on ? "var(--accent)" : "transparent", color: on ? "var(--on-accent)" : "var(--ink)" }}>
                <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: ".08em", opacity: .85 }}>{d.d}</div>
                <div style={{ fontSize: 22, fontWeight: 900, marginTop: 3 }}>{d.n}</div>
              </button>
            );
          })}
        </div>

        <Eyebrow accent style={{ marginBottom: 16 }}>A que horas</Eyebrow>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 10, marginBottom: 38 }}>
          {times.map(t => <button key={t} className={"chip" + (time === t ? " on" : "")} onClick={() => setTime(t)} style={{ minWidth: 76, textAlign: "center" }}>{t}</button>)}
        </div>

        <Eyebrow accent style={{ marginBottom: 16 }}>Quantos são</Eyebrow>
        <div className="seg">{[2, 3, 4, 6].map(n => <button key={n} className={size === n ? "on" : ""} onClick={() => setSize(n)}>{n === 6 ? "6+" : n}</button>)}</div>
      </div>

      <div className="reserve-summary card" style={{ padding: 26, position: "sticky", top: "calc(var(--nav-h) + 24px)" }}>
        <Eyebrow accent style={{ marginBottom: 18 }}>A tua reserva</Eyebrow>
        <SumLine l="Onde" r={v.t} />
        <SumLine l="Dia" r={`${days[day].d} ${days[day].n} jun`} />
        <SumLine l="Hora" r={time} />
        <SumLine l="Mesa" r={`${size}${size === 6 ? "+" : ""} ${size > 1 ? "pessoas" : "pessoa"}`} />
        <div className="divider" style={{ margin: "18px 0" }} />
        <p className="cap" style={{ marginBottom: 18, lineHeight: 1.5 }}>{v.note === "omakase" ? "Sem ementa — o chef decide por ti." : "A casa guarda-te o lugar. Sem stress."}</p>
        <Button variant="primary" block onClick={() => setDone(true)} icon="arrowR">Pedir mesa</Button>
      </div>
    </div>
  );
}

// ---- private spaces & buyout ----
function PrivateReserve({ D }) {
  const [space, setSpace] = React.useState("sala");
  const [occ, setOcc] = React.useState("Jantar privado");
  const [guests, setGuests] = React.useState("15");
  const [day, setDay] = React.useState("");
  const [note, setNote] = React.useState("");
  const [done, setDone] = React.useState(false);
  const sp = D.privates.find(x => x.id === space);
  if (done) return <PrivateDone D={D} sp={sp} occ={occ} onAgain={() => setDone(false)} />;

  return (
    <div className="reserve-grid" style={{ display: "grid", gridTemplateColumns: "1fr 360px", gap: 40, alignItems: "start" }}>
      <div>
        <Eyebrow accent style={{ marginBottom: 16 }}>O espaço</Eyebrow>
        <div className="priv-grid" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginBottom: 40 }}>
          {D.privates.map(x => {
            const on = space === x.id;
            return (
              <button key={x.id} onClick={() => setSpace(x.id)} className="card" style={{ padding: 0, cursor: "pointer", textAlign: "left",
                fontFamily: "inherit", overflow: "hidden", border: "1px solid " + (on ? "var(--accent)" : "var(--line)"),
                background: on ? "var(--surface-2)" : "var(--surface)" }}>
                <Photo ground={x.ground} height={120}>
                  {on && <div style={{ position: "absolute", top: 12, right: 12, width: 24, height: 24, borderRadius: 999, background: "var(--accent)",
                    color: "var(--on-accent)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="check" size={14} stroke={2.6} /></div>}
                  <div style={{ position: "absolute", left: 14, bottom: 12 }}><Tag tone="accent" style={{ background: "rgba(16,10,7,0.82)", color: "#F4E8D2", border: "1px solid rgba(244,232,210,0.30)", backdropFilter: "blur(6px)" }}>{x.cap}</Tag></div>
                </Photo>
                <div style={{ padding: "16px 18px" }}>
                  <h3 className="h3" style={{ fontSize: 16 }}>{x.t}</h3>
                  <p className="cap" style={{ marginTop: 5, lineHeight: 1.45 }}>{x.sub}</p>
                </div>
              </button>
            );
          })}
        </div>

        <Eyebrow accent style={{ marginBottom: 16 }}>A ocasião</Eyebrow>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 10, marginBottom: 38 }}>
          {D.occasions.map(o => <button key={o} className={"chip" + (occ === o ? " on" : "")} onClick={() => setOcc(o)}>{o}</button>)}
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 32, marginBottom: 38 }} className="priv-fields">
          <div>
            <Eyebrow accent style={{ marginBottom: 16 }}>Quantos convidados</Eyebrow>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 10 }}>
              {D.guestCounts.map(g => <button key={g} className={"chip" + (guests === g ? " on" : "")} onClick={() => setGuests(g)} style={{ minWidth: 58, textAlign: "center" }}>{g}</button>)}
            </div>
          </div>
          <Field label="Data pretendida" v={day} on={setDay} ph="ex. 12 de julho, almoço" />
        </div>

        <Field label="O que têm em mente (opcional)" textarea rows={3} v={note} on={setNote} ph="Aniversário da empresa, 40 pessoas, queremos a esplanada e omakase a meio…" />
      </div>

      <div className="reserve-summary card" style={{ padding: 26, position: "sticky", top: "calc(var(--nav-h) + 24px)" }}>
        <Eyebrow accent style={{ marginBottom: 18 }}>O vosso evento</Eyebrow>
        <SumLine l="Espaço" r={sp.t} />
        <SumLine l="Capacidade" r={sp.cap} />
        <SumLine l="Ocasião" r={occ} />
        <SumLine l="Convidados" r={guests + " pessoas"} />
        {day && <SumLine l="Data" r={day} />}
        <div className="divider" style={{ margin: "18px 0" }} />
        <p className="cap" style={{ marginBottom: 18, lineHeight: 1.5 }}>Eventos privados são desenhados à mão. Enviamos uma proposta em 24h — menu, bebida e tempos.</p>
        <Button variant="primary" block onClick={() => setDone(true)} icon="arrowR">Pedir proposta</Button>
        <p style={{ textAlign: "center", marginTop: 12 }}><span className="cap">ou fala já com a Mariko no Concierge</span></p>
      </div>
    </div>
  );
}
function PrivateDone({ D, sp, occ, onAgain }) {
  return (
    <div className="rise" style={{ textAlign: "center", maxWidth: 500, margin: "30px auto", position: "relative" }}>
      <Brush size={60} color="var(--accent)" style={{ margin: "0 auto 26px" }} />
      <Eyebrow accent>Pedido recebido</Eyebrow>
      <h1 className="h1" style={{ margin: "14px 0 0" }}>Vamos desenhar a vossa noite.</h1>
      <div className="rule" style={{ margin: "22px auto" }} />
      <p className="body-lg" style={{ maxWidth: 400, margin: "0 auto 36px" }}>
        {sp.t} · {occ}. A casa volta a vós em <strong style={{ color: "var(--ink)" }}>24 horas</strong> com uma proposta — menu, bebida e os tempos da noite.
      </p>
      <Button variant="primary" onClick={onAgain} icon="arrowR" style={{ minWidth: 240 }}>Pedir outro espaço</Button>
    </div>
  );
}
function SumLine({ l, r }) {
  return <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 12 }}>
    <span className="cap">{l}</span><span className="small" style={{ color: "var(--ink)", fontWeight: 700 }}>{r}</span></div>;
}
function BookingCard({ date, t, s, tag, dim }) {
  return (
    <div className="card" style={{ padding: 22 }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
        <Eyebrow>{date}</Eyebrow><Tag tone={dim ? "dim" : "accent"}>{tag}</Tag>
      </div>
      <h3 className="h3" style={{ margin: "12px 0 5px" }}>{t}</h3>
      <p className="cap">{s}</p>
      <div className="divider" style={{ margin: "16px 0" }} />
      <div style={{ display: "flex", gap: 20 }}>
        <button style={linkBtn}>Alterar</button><button style={{ ...linkBtn, color: "var(--ink-3)" }}>Cancelar</button>
      </div>
    </div>
  );
}
function ReserveDone({ D, v, day, time, size, onAgain }) {
  return (
    <Page>
      <div className="rise" style={{ textAlign: "center", maxWidth: 480, margin: "40px auto", position: "relative" }}>
        <div style={{ width: 76, height: 76, borderRadius: 999, margin: "0 auto 26px", background: "var(--accent)", color: "var(--on-accent)",
          display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="check" size={34} stroke={2.4} /></div>
        <Eyebrow accent>Está guardado</Eyebrow>
        <h1 className="h1" style={{ margin: "14px 0 0" }}>{v.t}.</h1>
        <div className="rule" style={{ margin: "22px auto" }} />
        <p className="body-lg" style={{ maxWidth: 360, margin: "0 auto 36px" }}>
          {day.d} {day.n} jun, {time} · {size} {size > 1 ? "pessoas" : "pessoa"}. A casa abre-te espaço.{v.note === "omakase" && " O chef já está a pensar no que te servir."}
        </p>
        <Button variant="primary" onClick={onAgain} icon="arrowR" style={{ minWidth: 240 }}>Ver as minhas reservas</Button>
      </div>
    </Page>
  );
}

// ───────────────────────── Pedidos ─────────────────────────
function Order({ D }) {
  const [cart, setCart] = React.useState({});
  const [sent, setSent] = React.useState(false);
  const add = id => { setSent(false); setCart(c => ({ ...c, [id]: (c[id] || 0) + 1 })); };
  const sub = id => setCart(c => { const n = { ...c }; if (n[id] > 1) n[id]--; else delete n[id]; return n; });
  const count = Object.values(cart).reduce((a, b) => a + b, 0);
  const total = D.menu.reduce((s, m) => s + (cart[m.id] || 0) * m.price, 0);

  return (
    <Page>
      <SectionHead eyebrow="Pede à casa" title="Pedidos." sub="Manda vir antes de chegar. A tua garrafa fica guardada com o teu nome." />

      <Eyebrow accent style={{ marginBottom: 16 }}>A tua garrafa guardada</Eyebrow>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill,minmax(300px,1fr))", gap: 14, marginBottom: 48 }}>
        {D.bottles.map(b => (
          <div key={b.id} className="card" style={{ padding: 18, display: "flex", alignItems: "center", gap: 16 }}>
            <div style={{ width: 42, height: 42, borderRadius: 999, background: "color-mix(in srgb, var(--accent) 10%, transparent)",
              border: "1px solid var(--line)", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--accent)", flexShrink: 0 }}><Icon name="bottle" size={20} /></div>
            <div style={{ flex: 1 }}><div className="h3" style={{ fontSize: 16 }}>{b.t}</div><div className="cap" style={{ marginTop: 3 }}>{b.sub} · {b.since}</div></div>
            <button style={linkBtn}>Pedir</button>
          </div>
        ))}
      </div>

      <div className="order-grid" style={{ display: "grid", gridTemplateColumns: "1fr 340px", gap: 40, alignItems: "start" }}>
        <div>
          <Eyebrow accent style={{ marginBottom: 8 }}>Manda vir</Eyebrow>
          {D.menu.map(m => {
            const q = cart[m.id] || 0;
            return (
              <div key={m.id} style={{ display: "flex", alignItems: "center", gap: 16, padding: "18px 0", borderBottom: "1px solid var(--line)" }}>
                <div style={{ flex: 1 }}><div className="h3" style={{ fontSize: 16 }}>{m.t}</div><div className="cap" style={{ marginTop: 4 }}>{m.sub}</div></div>
                <span className="small" style={{ color: "var(--ink)", fontWeight: 700 }}>{m.price}€</span>
                {q === 0
                  ? <button onClick={() => add(m.id)} aria-label="adicionar" style={stepBtn}><Icon name="plus" size={16} stroke={2} /></button>
                  : <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                      <button onClick={() => sub(m.id)} style={stepBtn}>−</button>
                      <span style={{ fontWeight: 900, minWidth: 14, textAlign: "center" }}>{q}</span>
                      <button onClick={() => add(m.id)} style={{ ...stepBtn, background: "var(--accent)", color: "var(--on-accent)", border: "none" }}>+</button>
                    </div>}
              </div>
            );
          })}
        </div>

        <div className="order-tab card" style={{ padding: 26, position: "sticky", top: "calc(var(--nav-h) + 24px)" }}>
          <Eyebrow accent style={{ marginBottom: 16 }}>A tua conta</Eyebrow>
          {count === 0
            ? <p className="small" style={{ marginBottom: 18 }}>Ainda não pediste nada. Escolhe ao lado.</p>
            : <>
                {D.menu.filter(m => cart[m.id]).map(m => (
                  <div key={m.id} style={{ display: "flex", justifyContent: "space-between", marginBottom: 10 }}>
                    <span className="small">{cart[m.id]}× {m.t}</span><span className="small num" style={{ color: "var(--ink)" }}>{cart[m.id] * m.price}€</span>
                  </div>
                ))}
                <div className="divider" style={{ margin: "16px 0" }} />
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 18 }}>
                  <span className="h3">Total</span><span className="display num" style={{ fontSize: 28 }}>{total}€</span>
                </div>
              </>}
          <Button variant="primary" block disabled={count === 0} onClick={() => setSent(true)}>{sent ? "Enviado à cozinha" : "Mandar à cozinha"}</Button>
          <div style={{ display: "flex", gap: 10, alignItems: "flex-start", marginTop: 18 }}>
            <Icon name="spark" size={16} style={{ color: "var(--accent)", flexShrink: 0, marginTop: 2 }} />
            <span className="cap" style={{ lineHeight: 1.5 }}><strong style={{ color: "var(--ink)" }}>A conta resolve-se.</strong> Acerta-se no fim do mês — sem cartões à mesa.</span>
          </div>
        </div>
      </div>
    </Page>
  );
}
const stepBtn = { width: 36, height: 36, borderRadius: 999, background: "transparent", border: "1px solid var(--line-2)",
  color: "var(--ink)", cursor: "pointer", fontSize: 18, fontFamily: "inherit", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 };

// ───────────────────────── Concierge ─────────────────────────
function Chat({ D }) {
  const [msgs, setMsgs] = React.useState(D.chatSeed.map((m, i) => ({ ...m, id: i })));
  const [txt, setTxt] = React.useState("");
  const endRef = React.useRef(null);
  React.useEffect(() => { if (endRef.current) endRef.current.scrollTop = endRef.current.scrollHeight; }, [msgs]);

  const send = (t) => {
    const text = (t || txt).trim(); if (!text) return;
    setTxt(""); const id = Date.now();
    setMsgs(m => [...m, { from: "me", t: text, id, time: "agora" }]);
    setTimeout(() => setMsgs(m => [...m, { from: "host", t: pickReply(text), id: id + 1, time: "agora" }]), 900);
  };

  return (
    <Page style={{ maxWidth: 760 }}>
      <div className="card" style={{ padding: 0, overflow: "hidden", display: "flex", flexDirection: "column", height: "min(72vh, 680px)" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 14, padding: "20px 24px", borderBottom: "1px solid var(--line)" }}>
          <div style={{ width: 44, height: 44, borderRadius: 999, background: "var(--accent)", color: "var(--on-accent)", display: "flex",
            alignItems: "center", justifyContent: "center", fontWeight: 900, fontSize: 16, flexShrink: 0 }}>M</div>
          <div style={{ flex: 1 }}>
            <div className="h3" style={{ fontSize: 17 }}>{D.host.name}</div>
            <div className="cap" style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 2 }}>
              <span style={{ width: 6, height: 6, borderRadius: 999, background: "var(--accent)" }} />{D.host.role}</div>
          </div>
        </div>

        <div ref={endRef} className="noscroll" style={{ flex: 1, overflowY: "auto", padding: "22px 24px" }}>
          <p className="cap" style={{ textAlign: "center", marginBottom: 20 }}>Uma linha direta com a casa. Respondemos depressa.</p>
          {msgs.map(m => <Bubble key={m.id} m={m} />)}
        </div>

        <div style={{ padding: "14px 18px 18px", borderTop: "1px solid var(--line)" }}>
          <div className="noscroll" style={{ display: "flex", gap: 8, overflowX: "auto", marginBottom: 12 }}>
            {D.chatSuggestions.map(s => <button key={s} className="chip" onClick={() => send(s)} style={{ flexShrink: 0, padding: "8px 14px", fontSize: 13 }}>{s}</button>)}
          </div>
          <div style={{ display: "flex", gap: 10 }}>
            <input className="box" value={txt} onChange={e => setTxt(e.target.value)} onKeyDown={e => e.key === "Enter" && send()}
              placeholder="Escreve à Mariko…" style={{ flex: 1, borderRadius: 999, padding: "13px 18px" }} />
            <button onClick={() => send()} aria-label="enviar" style={{ width: 48, height: 48, borderRadius: 999, flexShrink: 0, background: "var(--accent)",
              color: "var(--on-accent)", border: "none", cursor: "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="arrowR" size={20} stroke={2.2} /></button>
          </div>
        </div>
      </div>
    </Page>
  );
}
function pickReply(t) {
  const s = t.toLowerCase();
  if (s.includes("sexta") || s.includes("guarda")) return "Feito. Guardo-te dois bancos ao balcão, sexta às 20:30. O chef trata do resto.";
  if (s.includes("novo") || s.includes("há")) return "Esta semana: pipa de sake nama de Niigata, e o Aoki vem ao robata sexta. Queres entrar?";
  if (s.includes("mesa") || s.includes("hoje") || s.includes("dois")) return "Hoje há lugar, sempre há para um membro. A que horas chegas?";
  return "Anotado. Trato disso e volto já com confirmação — fica descansado.";
}
function Bubble({ m }) {
  const me = m.from === "me";
  return (
    <div className="fade" style={{ display: "flex", justifyContent: me ? "flex-end" : "flex-start", marginBottom: 12 }}>
      <div style={{ maxWidth: "76%" }}>
        <div style={{ padding: "12px 16px", borderRadius: me ? "14px 14px 4px 14px" : "14px 14px 14px 4px",
          background: me ? "var(--accent)" : "var(--bg-2)", color: me ? "var(--on-accent)" : "var(--ink)",
          border: me ? "none" : "1px solid var(--line)", fontSize: 15, lineHeight: 1.5 }}>{m.t}</div>
        <div className="cap" style={{ textAlign: me ? "right" : "left", marginTop: 5, fontSize: 11 }}>{m.time}</div>
      </div>
    </div>
  );
}

Object.assign(window, { Reserve, SumLine, BookingCard, ReserveDone, Order, stepBtn, Chat, pickReply, Bubble });
