/* Wood OS — Orçamentos (funil de venda) */
const { useState: useStateQ, useMemo: useMemoQ, useEffect: useEffectQ } = React;

/* ============================================================
   Status meta + helpers
   ============================================================ */
const QUOTE_STATUS_META = {
  rascunho:   { label: "Rascunho",   dot: "#737373", bg: "rgba(115,115,115,0.14)", fg: "#A3A3A3", icon: "edit" },
  enviado:    { label: "Enviado",    dot: "#38BDF8", bg: "rgba(56,189,248,0.12)",  fg: "#38BDF8", icon: "send" },
  aprovado:   { label: "Aprovado",   dot: "#22C55E", bg: "rgba(34,197,94,0.14)",   fg: "#22C55E", icon: "check-circle" },
  convertido: { label: "Convertido", dot: "#10B981", bg: "rgba(16,185,129,0.18)",  fg: "#10B981", icon: "hammer" },
  recusado:   { label: "Recusado",   dot: "#EF4444", bg: "rgba(239,68,68,0.12)",   fg: "#EF4444", icon: "x" },
  expirado:   { label: "Expirado",   dot: "#F59E0B", bg: "rgba(245,158,11,0.14)",  fg: "#F59E0B", icon: "clock" },
};

const ITEM_CATEGORY_META = {
  marcenaria:  { label: "Marcenaria",   color: "#34D399", icon: "hammer" },
  tampos:      { label: "Tampos",       color: "#38BDF8", icon: "ruler" },
  ferragem:    { label: "Ferragem",     color: "#F59E0B", icon: "settings" },
  acabamento:  { label: "Acabamento",   color: "#A78BFA", icon: "spark" },
  mao_de_obra: { label: "Mão de obra",  color: "#F472B6", icon: "users" },
};

const quoteSubtotal = (q) => q.items.reduce((s, i) => s + i.qty * i.unitPrice, 0);
const quoteTotal = (q) => {
  const sub = quoteSubtotal(q);
  const afterDisc = sub * (1 - (q.discount || 0) / 100);
  return afterDisc * (1 + (q.taxes || 0) / 100);
};

/* ============================================================
   QuotesPage
   ============================================================ */
const QuotesPage = ({ navigate }) => {
  const [status, setStatus] = useStateQ("todos");
  const [q, setQ] = useStateQ("");
  const [view, setView] = useStateQ("list");
  const [drawer, setDrawer] = useStateQ(null);

  const quotes = MOCK.quotes;

  const filtered = useMemoQ(() => quotes.filter(o => {
    if (status !== "todos" && o.status !== status) return false;
    if (q && !`${o.id} ${o.title} ${o.clientName}`.toLowerCase().includes(q.toLowerCase())) return false;
    return true;
  }), [quotes, status, q]);

  const counts = useMemoQ(() => {
    const c = { todos: quotes.length };
    quotes.forEach(o => { c[o.status] = (c[o.status] || 0) + 1; });
    return c;
  }, [quotes]);

  const metrics = useMemoQ(() => {
    const open = quotes.filter(o => o.status === "rascunho" || o.status === "enviado");
    const aprovados = quotes.filter(o => o.status === "aprovado" || o.status === "convertido");
    const recusados = quotes.filter(o => o.status === "recusado");
    const decididos = aprovados.length + recusados.length;
    const pipeline = open.reduce((s, o) => s + quoteTotal(o), 0);
    const aprovadoMes = aprovados.filter(o => (o.approvedAt || "").startsWith("2026-05")).reduce((s, o) => s + quoteTotal(o), 0);
    return {
      open: open.length,
      pipeline,
      aprovadoMes,
      taxa: decididos ? Math.round((aprovados.length / decididos) * 100) : 0,
    };
  }, [quotes]);

  return (
    <>
      <PageHeader
        kicker="Operacional"
        title="Orçamentos"
        subtitle="Funil de venda da marcenaria. Acompanhe pipeline, prazos de validade e conversão em obra."
        actions={
          <>
            <div className="iflex items-center" style={{ background: "var(--wood-surface-2)", border: "1px solid var(--wood-border)", borderRadius: 10, padding: 2 }}>
              <button onClick={() => setView("list")} className="wood-btn wood-btn-ghost wood-btn-sm" style={{ background: view === "list" ? "rgba(16,185,129,0.16)" : "transparent", color: view === "list" ? "var(--cream)" : undefined }}>
                <Icon name="log" size={13} /> Lista
              </button>
              <button onClick={() => setView("funnel")} className="wood-btn wood-btn-ghost wood-btn-sm" style={{ background: view === "funnel" ? "rgba(16,185,129,0.16)" : "transparent", color: view === "funnel" ? "var(--cream)" : undefined }}>
                <Icon name="layers" size={13} /> Funil
              </button>
            </div>
            <button className="wood-btn wood-btn-secondary"><Icon name="external" size={13} /> Exportar</button>
            <button className="wood-btn wood-btn-primary" onClick={() => navigate("new-quote")}>
              <Icon name="plus" size={13} /> Novo orçamento
            </button>
          </>
        }
      />

      {/* KPIs */}
      <div className="grid grid-cols-4 gap-4 mb-5">
        <MetricCard icon="inbox" label="Em aberto" value={metrics.open} sub="rascunho + enviados" accent="info" delay={0} />
        <MetricCard icon="dollar" label="Pipeline" value={fmtBRL(metrics.pipeline)} sub="valor em aberto" accent="amber" delay={60} />
        <MetricCard icon="check-circle" label="Aprovado no mês" value={fmtBRL(metrics.aprovadoMes)} sub="orçamentos fechados em maio" accent="success" delay={120} />
        <MetricCard icon="trend-up" label="Taxa de conversão" value={`${metrics.taxa}%`} sub="aprovados / decididos" accent="success" delay={180} />
      </div>

      {/* Filters */}
      <div className="wood-card p-3 mb-4 flex items-center gap-2 flex-wrap">
        <FilterChip active={status === "todos"} onClick={() => setStatus("todos")} count={counts.todos}>Todos</FilterChip>
        {Object.entries(QUOTE_STATUS_META).map(([k, m]) => (
          <FilterChip key={k} active={status === k} onClick={() => setStatus(k)} count={counts[k] || 0}>{m.label}</FilterChip>
        ))}
        <div className="wood-divider md-hide" style={{ width: 1, height: 24, background: "var(--wood-border)" }} />
        <div className="flex items-center gap-2 flex-1" style={{ minWidth: 200 }}>
          <Icon name="search" size={14} className="text-3" />
          <input
            className="flex-1"
            style={{ background: "transparent", border: "none", outline: "none", fontSize: 13, color: "var(--text)" }}
            placeholder="Buscar por número, título ou cliente…"
            value={q}
            onChange={e => setQ(e.target.value)}
          />
        </div>
      </div>

      {filtered.length === 0 ? (
        <EmptyState icon="file-text" title="Nenhum orçamento" description="Ajuste os filtros ou crie um novo orçamento." />
      ) : view === "list" ? (
        <QuoteList items={filtered} onOpen={setDrawer} />
      ) : (
        <QuoteFunnel items={filtered} onOpen={setDrawer} />
      )}

      <PremiumDrawer
        open={!!drawer}
        onClose={() => setDrawer(null)}
        title={drawer?.title}
        subtitle={drawer?.id}
        width={760}
        actions={
          <>
            <button className="wood-btn wood-btn-ghost"><Icon name="external" size={13} /> Baixar PDF</button>
            <button className="wood-btn wood-btn-ghost"><Icon name="send" size={13} /> Enviar por email</button>
            <div className="flex-1" />
            <button className="wood-btn wood-btn-secondary" onClick={() => setDrawer(null)}>Fechar</button>
            {drawer?.status === "rascunho" && <button className="wood-btn wood-btn-primary"><Icon name="send" size={13} /> Enviar ao cliente</button>}
            {drawer?.status === "enviado" && <button className="wood-btn wood-btn-primary"><Icon name="check" size={13} /> Marcar aprovado</button>}
            {drawer?.status === "aprovado" && <button className="wood-btn wood-btn-primary"><Icon name="hammer" size={13} /> Converter em obra</button>}
          </>
        }
      >
        {drawer && <QuotePreview q={drawer} />}
      </PremiumDrawer>
    </>
  );
};

/* ============================================================
   QuoteList — table view
   ============================================================ */
const QuoteList = ({ items, onOpen }) => (
  <div className="wood-card" style={{ padding: 0, overflow: "hidden" }}>
    <table className="wood-table">
      <thead>
        <tr>
          <th>Número</th>
          <th>Orçamento</th>
          <th>Cliente</th>
          <th>Valor</th>
          <th>Validade</th>
          <th>Status</th>
          <th>Responsável</th>
        </tr>
      </thead>
      <tbody>
        {items.map(o => {
          const st = QUOTE_STATUS_META[o.status] || QUOTE_STATUS_META.rascunho;
          const total = quoteTotal(o);
          const dleft = daysUntil(o.validUntil);
          const expired = dleft < 0 && (o.status === "enviado" || o.status === "rascunho");
          return (
            <tr key={o.id} onClick={() => onOpen(o)} style={{ cursor: "pointer" }}>
              <td className="font-mono text-3" style={{ fontSize: 12 }}>{o.id}</td>
              <td>
                <div style={{ fontWeight: 600, color: "var(--text)" }}>{o.title}</div>
                <div className="text-xs text-4">{o.items.length} itens · {fmtDate(o.createdAt)}</div>
              </td>
              <td>
                <div className="flex items-center gap-2">
                  <Avatar name={o.clientName} size={24} />
                  <span className="text-sm">{o.clientName}</span>
                </div>
              </td>
              <td>
                <div className="text-sm font-semibold" style={{ fontVariantNumeric: "tabular-nums" }}>{fmtBRL(total)}</div>
                {o.discount > 0 && <div className="text-xs text-amber">−{o.discount}% desconto</div>}
              </td>
              <td>
                <div className={`text-sm ${expired ? "text-error" : dleft <= 7 && (o.status === "enviado" || o.status === "rascunho") ? "text-warning" : ""}`} style={{ fontWeight: 500 }}>
                  {fmtDate(o.validUntil)}
                </div>
                {(o.status === "enviado" || o.status === "rascunho") && (
                  <div className="text-xs text-4">{expired ? `${Math.abs(dleft)}d vencido` : `${dleft}d restantes`}</div>
                )}
              </td>
              <td>
                <span className="wood-badge" style={{ background: st.bg, color: st.fg, padding: "2px 8px" }}>
                  <Icon name={st.icon} size={10} /> {st.label}
                </span>
              </td>
              <td>
                <div className="flex items-center gap-2">
                  <Avatar name={o.responsavel} size={22} />
                  <span className="text-sm">{o.responsavel.split(" ")[0]}</span>
                </div>
              </td>
            </tr>
          );
        })}
      </tbody>
    </table>
  </div>
);

/* ============================================================
   QuoteFunnel — kanban-style funnel view
   ============================================================ */
const QuoteFunnel = ({ items, onOpen }) => {
  const cols = ["rascunho", "enviado", "aprovado", "convertido"];
  return (
    <div className="grid gap-4" style={{ gridTemplateColumns: `repeat(${cols.length}, minmax(0,1fr))` }}>
      {cols.map(col => {
        const colItems = items.filter(o => o.status === col);
        const colTotal = colItems.reduce((s, o) => s + quoteTotal(o), 0);
        const st = QUOTE_STATUS_META[col];
        return (
          <div key={col} className="wood-card p-3" style={{ background: "rgba(0,0,0,0.18)" }}>
            <div className="flex items-center justify-between mb-3 px-1">
              <div className="flex items-center gap-2">
                <span className="wood-dot" style={{ background: st.dot }} />
                <span className="text-sm" style={{ fontWeight: 600 }}>{st.label}</span>
              </div>
              <span className="text-xs text-3" style={{ fontVariantNumeric: "tabular-nums" }}>{colItems.length}</span>
            </div>
            <div className="text-xs text-4 px-1 mb-3" style={{ fontVariantNumeric: "tabular-nums" }}>
              {colTotal > 0 ? fmtBRL(colTotal) : "—"}
            </div>
            <div className="flex flex-col gap-2">
              {colItems.length === 0 ? (
                <div className="text-xs text-4 text-center py-8">Vazio</div>
              ) : colItems.map(o => {
                const total = quoteTotal(o);
                const dleft = daysUntil(o.validUntil);
                return (
                  <div key={o.id} onClick={() => onOpen(o)}
                       className="px-3 py-3 rounded-lg cursor-pointer"
                       style={{ background: "rgba(20,20,20,0.7)", border: "1px solid var(--wood-border-soft)", transition: "transform 0.18s, border-color 0.18s" }}
                       onMouseEnter={e => { e.currentTarget.style.borderColor = "var(--amber-bright)"; e.currentTarget.style.transform = "translateY(-1px)"; }}
                       onMouseLeave={e => { e.currentTarget.style.borderColor = "var(--wood-border-soft)"; e.currentTarget.style.transform = "translateY(0)"; }}>
                    <div className="font-mono text-xs text-4 mb-1">{o.id}</div>
                    <div className="text-sm mb-2" style={{ fontWeight: 600, lineHeight: 1.3 }}>{o.title}</div>
                    <div className="text-xs text-3 truncate mb-2">{o.clientName}</div>
                    <div className="flex items-center justify-between">
                      <span className="text-sm" style={{ fontWeight: 600, fontVariantNumeric: "tabular-nums", color: "var(--amber-bright)" }}>{fmtBRL(total)}</span>
                      {(col === "rascunho" || col === "enviado") && (
                        <span className={`text-xs ${dleft < 0 ? "text-error" : dleft <= 7 ? "text-warning" : "text-4"}`}>
                          {dleft < 0 ? `${Math.abs(dleft)}d vencido` : `${dleft}d`}
                        </span>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        );
      })}
    </div>
  );
};

/* ============================================================
   QuotePreview — PDF-like detail in drawer
   ============================================================ */
const QuotePreview = ({ q }) => {
  const sub = quoteSubtotal(q);
  const disc = sub * ((q.discount || 0) / 100);
  const baseTaxes = sub - disc;
  const taxes = baseTaxes * ((q.taxes || 0) / 100);
  const total = baseTaxes + taxes;
  const st = QUOTE_STATUS_META[q.status];
  const dleft = daysUntil(q.validUntil);
  const grouped = useMemoQ(() => {
    const g = {};
    q.items.forEach(i => { (g[i.category] = g[i.category] || []).push(i); });
    return g;
  }, [q]);

  return (
    <div>
      {/* Status banner */}
      <div className="wood-card wood-veneer p-4 mb-5 flex items-center justify-between" style={{ background: `${st.bg}`, borderColor: st.fg + "44" }}>
        <div className="flex items-center gap-3">
          <div style={{ width: 40, height: 40, borderRadius: 10, background: st.bg, color: st.fg, border: `1px solid ${st.fg}55`, display: "inline-flex", alignItems: "center", justifyContent: "center" }}>
            <Icon name={st.icon} size={18} />
          </div>
          <div>
            <div className="text-xs text-3 uppercase tracking-widest" style={{ fontWeight: 500 }}>STATUS</div>
            <div className="text-md font-semibold" style={{ color: st.fg }}>{st.label}</div>
          </div>
        </div>
        <div className="text-right">
          <div className="text-xs text-3 uppercase tracking-widest" style={{ fontWeight: 500 }}>VÁLIDO ATÉ</div>
          <div className={`text-md font-semibold ${dleft < 0 ? "text-error" : ""}`}>{fmtDateLong(q.validUntil)}</div>
        </div>
      </div>

      {/* Header (cabeçalho do PDF) */}
      <div className="wood-card p-6 mb-5" style={{ background: "rgba(0,0,0,0.32)" }}>
        <div className="flex items-start justify-between gap-4 mb-5 pb-4" style={{ borderBottom: "1px solid var(--wood-border)" }}>
          <div>
            <div className="flex items-center gap-2 mb-2">
              <WoodLogo size={28} textSize={14} showText={true} />
            </div>
            <div className="text-xs text-3 mt-2 leading-relaxed">
              Marcenaria Norte LTDA<br />
              CNPJ 12.345.678/0001-90 · contato@marcenarianorte.com.br<br />
              Rua dos Inhambus, 124 · Tijuca · Rio de Janeiro/RJ
            </div>
          </div>
          <div className="text-right">
            <div className="text-xs uppercase tracking-widest text-amber" style={{ fontWeight: 600 }}>ORÇAMENTO</div>
            <div className="font-mono text-xl font-semibold tracking-tight">{q.id}</div>
            <div className="text-xs text-4 mt-1">Emitido em {fmtDateLong(q.createdAt)}</div>
          </div>
        </div>

        <div className="grid grid-cols-2 gap-4">
          <div>
            <div className="text-xs text-4 uppercase tracking-widest mb-2" style={{ fontWeight: 500 }}>PARA</div>
            <div className="text-md font-semibold tracking-tight">{q.clientName}</div>
            <div className="text-xs text-3 mt-1">{q.project || "—"}</div>
          </div>
          <div>
            <div className="text-xs text-4 uppercase tracking-widest mb-2" style={{ fontWeight: 500 }}>RESPONSÁVEL</div>
            <div className="text-md font-semibold tracking-tight">{q.responsavel}</div>
            <div className="text-xs text-3 mt-1">eduardo@marcenarianorte.com.br</div>
          </div>
        </div>
      </div>

      {/* Items table */}
      <div className="mb-5">
        <div className="text-sm font-semibold mb-3">Itens do orçamento</div>
        {Object.entries(grouped).map(([cat, list]) => {
          const meta = ITEM_CATEGORY_META[cat] || ITEM_CATEGORY_META.marcenaria;
          const catTotal = list.reduce((s, i) => s + i.qty * i.unitPrice, 0);
          return (
            <div key={cat} className="mb-3">
              <div className="flex items-center justify-between px-3 py-2 rounded-t-lg" style={{ background: `${meta.color}14`, border: `1px solid ${meta.color}33`, borderBottom: "none" }}>
                <div className="flex items-center gap-2" style={{ color: meta.color, fontWeight: 600, fontSize: 12, textTransform: "uppercase", letterSpacing: "0.06em" }}>
                  <Icon name={meta.icon} size={12} /> {meta.label}
                </div>
                <div className="text-xs" style={{ color: meta.color, fontVariantNumeric: "tabular-nums", fontWeight: 600 }}>{fmtBRL(catTotal)}</div>
              </div>
              <div className="rounded-b-lg" style={{ background: "rgba(0,0,0,0.18)", border: "1px solid var(--wood-border-soft)", borderTop: "none", overflow: "hidden" }}>
                {list.map((it, i) => (
                  <div key={i} className="flex items-center gap-3 px-3 py-2.5" style={{ borderBottom: i < list.length - 1 ? "1px solid var(--wood-border-soft)" : "none" }}>
                    <div className="flex-1 text-sm">{it.description}</div>
                    <div className="text-xs text-3" style={{ fontVariantNumeric: "tabular-nums", width: 80, textAlign: "right" }}>{it.qty} {it.unit}</div>
                    <div className="text-xs text-3" style={{ fontVariantNumeric: "tabular-nums", width: 110, textAlign: "right" }}>{fmtBRL(it.unitPrice)}</div>
                    <div className="text-sm" style={{ fontVariantNumeric: "tabular-nums", width: 130, textAlign: "right", fontWeight: 600 }}>{fmtBRL(it.qty * it.unitPrice)}</div>
                  </div>
                ))}
              </div>
            </div>
          );
        })}
      </div>

      {/* Totals */}
      <div className="wood-card wood-veneer p-5 mb-5" style={{ background: "rgba(16,185,129,0.04)" }}>
        <div className="flex flex-col gap-2">
          <div className="flex items-center justify-between text-sm">
            <span className="text-3">Subtotal</span>
            <span style={{ fontVariantNumeric: "tabular-nums" }}>{fmtBRL(sub)}</span>
          </div>
          {q.discount > 0 && (
            <div className="flex items-center justify-between text-sm">
              <span className="text-3">Desconto ({q.discount}%)</span>
              <span style={{ fontVariantNumeric: "tabular-nums", color: "var(--amber-bright)" }}>−{fmtBRL(disc)}</span>
            </div>
          )}
          {q.taxes > 0 && (
            <div className="flex items-center justify-between text-sm">
              <span className="text-3">Impostos ({q.taxes}%)</span>
              <span style={{ fontVariantNumeric: "tabular-nums" }}>+{fmtBRL(taxes)}</span>
            </div>
          )}
          <div className="flex items-center justify-between pt-3 mt-1" style={{ borderTop: "1px solid var(--wood-border)" }}>
            <span className="text-md font-semibold">Total</span>
            <span className="text-2xl font-semibold tracking-tight wood-gradient-text" style={{ fontVariantNumeric: "tabular-nums" }}>{fmtBRL(total)}</span>
          </div>
        </div>
      </div>

      {/* Conditions */}
      <div className="grid grid-cols-2 gap-3 mb-5">
        <div className="px-4 py-3 rounded-lg" style={{ background: "rgba(0,0,0,0.18)", border: "1px solid var(--wood-border-soft)" }}>
          <div className="text-xs text-4 uppercase tracking-widest mb-1.5" style={{ fontWeight: 500 }}>FORMA DE PAGAMENTO</div>
          <div className="text-sm" style={{ fontWeight: 500 }}>{q.paymentTerms}</div>
        </div>
        <div className="px-4 py-3 rounded-lg" style={{ background: "rgba(0,0,0,0.18)", border: "1px solid var(--wood-border-soft)" }}>
          <div className="text-xs text-4 uppercase tracking-widest mb-1.5" style={{ fontWeight: 500 }}>PRAZO DE ENTREGA</div>
          <div className="text-sm" style={{ fontWeight: 500 }}>{q.deliveryTerms}</div>
        </div>
      </div>

      {q.notes && (
        <div className="mb-2">
          <div className="text-sm font-semibold mb-2">Observações</div>
          <div className="p-4 rounded-lg text-sm text-2" style={{ background: "rgba(0,0,0,0.18)", border: "1px solid var(--wood-border-soft)" }}>
            {q.notes}
          </div>
        </div>
      )}
    </div>
  );
};

/* ============================================================
   NewQuotePage — quote builder
   ============================================================ */
const NewQuotePage = ({ navigate }) => {
  const [data, setData] = useStateQ({
    clientId: "",
    title: "",
    project: "",
    paymentTerms: "40% sinal, 30% início produção, 30% montagem",
    deliveryTerms: "30 dias úteis após aprovação",
    discount: 0,
    taxes: 5,
    notes: "",
    items: [{ description: "", category: "marcenaria", qty: 1, unit: "peça", unitPrice: 0 }],
  });
  const [submitted, setSubmitted] = useStateQ(false);

  const update = (k, v) => setData(d => ({ ...d, [k]: v }));
  const updateItem = (i, k, v) => setData(d => ({ ...d, items: d.items.map((it, j) => j === i ? { ...it, [k]: v } : it) }));
  const addItem = () => update("items", [...data.items, { description: "", category: "marcenaria", qty: 1, unit: "peça", unitPrice: 0 }]);
  const removeItem = (i) => update("items", data.items.filter((_, j) => j !== i));

  const sub = data.items.reduce((s, i) => s + (Number(i.qty) || 0) * (Number(i.unitPrice) || 0), 0);
  const disc = sub * ((Number(data.discount) || 0) / 100);
  const base = sub - disc;
  const taxes = base * ((Number(data.taxes) || 0) / 100);
  const total = base + taxes;

  const valid = data.clientId && data.title && data.items.some(i => i.description && Number(i.unitPrice) > 0);

  if (submitted) {
    return (
      <div className="flex items-center justify-center" style={{ minHeight: "60vh" }}>
        <div className="text-center max-w-md">
          <div style={{
            width: 80, height: 80, borderRadius: 22, margin: "0 auto 20px",
            background: "linear-gradient(135deg, rgba(16,185,129,0.18), rgba(2,44,34,0.4))",
            border: "1px solid rgba(16,185,129,0.45)",
            display: "inline-flex", alignItems: "center", justifyContent: "center",
            color: "var(--amber-bright)"
          }}>
            <Icon name="check" size={36} />
          </div>
          <h2 className="text-2xl font-semibold tracking-tight mb-2">Orçamento criado!</h2>
          <p className="text-3 mb-6">O orçamento foi salvo como rascunho. Você pode revisar e enviar quando estiver pronto.</p>
          <div className="flex items-center justify-center gap-2">
            <button className="wood-btn wood-btn-secondary" onClick={() => navigate("quotes")}>Ver orçamentos</button>
            <button className="wood-btn wood-btn-primary" onClick={() => { setSubmitted(false); setData({ ...data, items: [{ description: "", category: "marcenaria", qty: 1, unit: "peça", unitPrice: 0 }] }); }}>Criar outro</button>
          </div>
        </div>
      </div>
    );
  }

  const selectedClient = MOCK.clients.find(c => c.id === data.clientId);

  return (
    <>
      <PageHeader
        kicker="Operacional"
        title="Novo Orçamento"
        subtitle="Monte um orçamento detalhado com itens por categoria, condições comerciais e total calculado automaticamente."
      />

      <div className="grid grid-cols-12 gap-5">
        {/* Left: form */}
        <div className="col-span-8">
          <div className="wood-card p-6 mb-5">
            <h3 className="text-md font-semibold tracking-tight mb-4">Cliente e identificação</h3>
            <div className="grid grid-cols-2 gap-4 mb-4">
              <div>
                <label className="wood-label">Cliente</label>
                <select className="wood-select" value={data.clientId} onChange={e => update("clientId", e.target.value)}>
                  <option value="">Selecione um cliente…</option>
                  {MOCK.clients.map(c => <option key={c.id} value={c.id}>{c.name} ({c.type})</option>)}
                </select>
              </div>
              <div>
                <label className="wood-label">Obra vinculada (opcional)</label>
                <select className="wood-select" value={data.project} onChange={e => update("project", e.target.value)}>
                  <option value="">Sem obra ainda</option>
                  {MOCK.projects.map(p => <option key={p.id} value={p.name}>{p.name}</option>)}
                </select>
              </div>
            </div>
            <div>
              <label className="wood-label">Título do orçamento</label>
              <input className="wood-input" placeholder="Ex: Marcenaria completa — Cobertura Vieira Souto"
                value={data.title} onChange={e => update("title", e.target.value)} />
            </div>
          </div>

          <div className="wood-card p-6 mb-5">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-md font-semibold tracking-tight">Itens</h3>
              <span className="text-xs text-3">{data.items.length} {data.items.length === 1 ? "item" : "itens"}</span>
            </div>
            <div className="flex flex-col gap-3 mb-4">
              {data.items.map((it, i) => {
                const total = (Number(it.qty) || 0) * (Number(it.unitPrice) || 0);
                return (
                  <div key={i} className="rounded-lg p-3" style={{ background: "rgba(0,0,0,0.18)", border: "1px solid var(--wood-border-soft)" }}>
                    <div className="flex items-center gap-2 mb-3">
                      <span className="font-mono text-xs text-4">#{String(i + 1).padStart(2, "0")}</span>
                      <select className="wood-select" value={it.category} onChange={e => updateItem(i, "category", e.target.value)} style={{ height: 28, padding: "0 8px", fontSize: 12, maxWidth: 160 }}>
                        {Object.entries(ITEM_CATEGORY_META).map(([k, m]) => <option key={k} value={k}>{m.label}</option>)}
                      </select>
                      <div className="flex-1" />
                      <span className="text-sm font-semibold" style={{ fontVariantNumeric: "tabular-nums", color: total ? "var(--amber-bright)" : "var(--text-4)" }}>{total ? fmtBRL(total) : "—"}</span>
                      {data.items.length > 1 && (
                        <button type="button" className="wood-btn wood-btn-ghost wood-btn-icon-sm" onClick={() => removeItem(i)}>
                          <Icon name="trash" size={13} />
                        </button>
                      )}
                    </div>
                    <div className="grid grid-cols-12 gap-2">
                      <div style={{ gridColumn: "span 7" }}>
                        <input className="wood-input" placeholder="Descrição do item"
                          value={it.description} onChange={e => updateItem(i, "description", e.target.value)} />
                      </div>
                      <div style={{ gridColumn: "span 2" }}>
                        <input type="number" className="wood-input" placeholder="Qtd"
                          value={it.qty} onChange={e => updateItem(i, "qty", e.target.value)} />
                      </div>
                      <div style={{ gridColumn: "span 1" }}>
                        <select className="wood-select" value={it.unit} onChange={e => updateItem(i, "unit", e.target.value)} style={{ padding: "0 8px" }}>
                          <option>peça</option><option>un</option><option>m</option><option>m²</option><option>kg</option><option>hora</option><option>verba</option><option>módulo</option><option>kit</option>
                        </select>
                      </div>
                      <div style={{ gridColumn: "span 2" }}>
                        <input type="number" className="wood-input" placeholder="R$ unit."
                          value={it.unitPrice} onChange={e => updateItem(i, "unitPrice", e.target.value)} />
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
            <button type="button" className="wood-btn wood-btn-secondary w-full" onClick={addItem}>
              <Icon name="plus" size={13} /> Adicionar item
            </button>
          </div>

          <div className="wood-card p-6 mb-5">
            <h3 className="text-md font-semibold tracking-tight mb-4">Condições comerciais</h3>
            <div className="grid grid-cols-2 gap-4 mb-4">
              <div>
                <label className="wood-label">Forma de pagamento</label>
                <input className="wood-input" value={data.paymentTerms} onChange={e => update("paymentTerms", e.target.value)} />
              </div>
              <div>
                <label className="wood-label">Prazo de entrega</label>
                <input className="wood-input" value={data.deliveryTerms} onChange={e => update("deliveryTerms", e.target.value)} />
              </div>
            </div>
            <div className="grid grid-cols-2 gap-4 mb-4">
              <div>
                <label className="wood-label">Desconto (%)</label>
                <input type="number" className="wood-input" value={data.discount} min={0} max={100}
                  onChange={e => update("discount", e.target.value)} />
              </div>
              <div>
                <label className="wood-label">Impostos (%)</label>
                <input type="number" className="wood-input" value={data.taxes} min={0} max={50}
                  onChange={e => update("taxes", e.target.value)} />
              </div>
            </div>
            <div>
              <label className="wood-label">Observações (opcional)</label>
              <textarea className="wood-textarea" rows={3} placeholder="Notas internas, condições especiais, contexto do cliente…"
                value={data.notes} onChange={e => update("notes", e.target.value)} />
            </div>
          </div>

          <div className="flex items-center justify-between gap-2">
            <button className="wood-btn wood-btn-ghost" onClick={() => navigate("quotes")}>
              <Icon name="chevron-left" size={13} /> Cancelar
            </button>
            <div className="flex items-center gap-2">
              <button className="wood-btn wood-btn-secondary" disabled={!valid} onClick={() => setSubmitted(true)}>
                <Icon name="edit" size={13} /> Salvar rascunho
              </button>
              <button className="wood-btn wood-btn-primary" disabled={!valid} onClick={() => setSubmitted(true)}>
                <Icon name="send" size={13} /> Salvar e enviar
              </button>
            </div>
          </div>
        </div>

        {/* Right: live preview */}
        <div className="col-span-4">
          <div className="wood-card p-5 sticky" style={{ top: 80 }}>
            <div className="text-xs uppercase tracking-widest text-amber mb-2" style={{ fontWeight: 600 }}>RESUMO AO VIVO</div>

            {selectedClient ? (
              <div className="flex items-center gap-3 mb-4 p-3 rounded-lg" style={{ background: "rgba(16,185,129,0.06)", border: "1px solid rgba(16,185,129,0.18)" }}>
                <Avatar name={selectedClient.name} size={34} />
                <div className="min-w-0">
                  <div className="text-sm truncate" style={{ fontWeight: 600 }}>{selectedClient.name}</div>
                  <div className="text-xs text-3">{selectedClient.type === "PF" ? "Pessoa Física" : "Pessoa Jurídica"}</div>
                </div>
              </div>
            ) : (
              <div className="text-sm text-4 mb-4 italic">Sem cliente selecionado</div>
            )}

            <div className="text-md font-semibold tracking-tight mb-1" style={{ minHeight: 24 }}>{data.title || <span className="text-4 font-normal">Sem título</span>}</div>

            <div className="flex flex-col gap-2 mb-4 mt-4">
              <div className="flex items-center justify-between text-sm">
                <span className="text-3">Subtotal</span>
                <span style={{ fontVariantNumeric: "tabular-nums" }}>{fmtBRL(sub)}</span>
              </div>
              {Number(data.discount) > 0 && (
                <div className="flex items-center justify-between text-sm">
                  <span className="text-3">Desconto ({data.discount}%)</span>
                  <span style={{ fontVariantNumeric: "tabular-nums", color: "var(--amber-bright)" }}>−{fmtBRL(disc)}</span>
                </div>
              )}
              {Number(data.taxes) > 0 && (
                <div className="flex items-center justify-between text-sm">
                  <span className="text-3">Impostos ({data.taxes}%)</span>
                  <span style={{ fontVariantNumeric: "tabular-nums" }}>+{fmtBRL(taxes)}</span>
                </div>
              )}
              <div className="flex items-center justify-between pt-3" style={{ borderTop: "1px solid var(--wood-border)" }}>
                <span className="text-md font-semibold">Total</span>
                <span className="text-xl font-semibold tracking-tight wood-gradient-text" style={{ fontVariantNumeric: "tabular-nums" }}>{fmtBRL(total)}</span>
              </div>
            </div>

            <div className="text-xs text-3 leading-relaxed pt-3" style={{ borderTop: "1px solid var(--wood-border-soft)" }}>
              <Icon name="info" size={11} /> Validade padrão de 30 dias. Você pode ajustar depois de salvar.
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

/* expose */
Object.assign(window, { QuotesPage, NewQuotePage });
