/* Wood OS — Plano de Corte (otimização de chapa) */
const { useState: useStateCut, useMemo: useMemoCut } = React;

/* ============================================================
   Status meta
   ============================================================ */
const CUT_STATUS_META = {
  rascunho:     { label: "Rascunho",     dot: "#737373", bg: "rgba(115,115,115,0.14)", fg: "#A3A3A3", icon: "edit" },
  aprovado:     { label: "Aprovado",     dot: "#22C55E", bg: "rgba(34,197,94,0.14)",   fg: "#22C55E", icon: "check" },
  em_producao:  { label: "Em produção",  dot: "#10B981", bg: "rgba(16,185,129,0.16)",  fg: "#34D399", icon: "saw" },
  concluido:    { label: "Concluído",    dot: "#38BDF8", bg: "rgba(56,189,248,0.12)",  fg: "#38BDF8", icon: "check-circle" },
};

// Distinct hues so adjacent pieces on a sheet read at a glance
const PIECE_HUES = [
  "#34D399", "#38BDF8", "#A78BFA", "#F472B6", "#F59E0B",
  "#FB923C", "#22D3EE", "#86EFAC", "#FCD34D", "#C084FC",
  "#F87171", "#60A5FA", "#34D399", "#FBBF24", "#A3E635",
];

const pieceColor = (i) => PIECE_HUES[i % PIECE_HUES.length];

const planTotals = (p) => {
  const sheets = p.sheets.length;
  const pieces = p.sheets.reduce((s, sh) => s + sh.pieces.length, 0);
  const avgUsage = p.sheets.reduce((s, sh) => s + sh.usage, 0) / sheets;
  const sheetArea = p.sheetSize.w * p.sheetSize.h;
  const usedArea = p.sheets.reduce((s, sh) => s + sh.pieces.reduce((a, pc) => a + pc.w * pc.h, 0), 0);
  const wasteArea = sheetArea * sheets - usedArea;
  return { sheets, pieces, avgUsage, sheetArea, usedArea, wasteArea };
};

/* ============================================================
   CuttingPage
   ============================================================ */
const CuttingPage = ({ navigate }) => {
  const [status, setStatus] = useStateCut("todos");
  const [q, setQ] = useStateCut("");
  const [drawer, setDrawer] = useStateCut(null);
  const [creating, setCreating] = useStateCut(false);

  const plans = MOCK.cuttingPlans;

  const filtered = useMemoCut(() => plans.filter(p => {
    if (status !== "todos" && p.status !== status) return false;
    if (q && !`${p.id} ${p.title} ${p.projectName} ${p.material}`.toLowerCase().includes(q.toLowerCase())) return false;
    return true;
  }), [plans, status, q]);

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

  const metrics = useMemoCut(() => {
    const open = plans.filter(p => p.status === "rascunho" || p.status === "aprovado" || p.status === "em_producao").length;
    const totalSheets = plans.reduce((s, p) => s + p.sheets.length, 0);
    const allSheets = plans.flatMap(p => p.sheets);
    const avgUsage = allSheets.reduce((s, sh) => s + sh.usage, 0) / (allSheets.length || 1);
    // Estimated saving vs. naive (assume 70% baseline)
    const savingPct = avgUsage - 70;
    return { open, totalSheets, avgUsage, savingPct };
  }, [plans]);

  return (
    <>
      <PageHeader
        kicker="Produção"
        title="Plano de Corte"
        subtitle="Otimização do aproveitamento de chapa por obra. Cada peça posicionada para minimizar sobras e perdas."
        actions={
          <>
            <button className="wood-btn wood-btn-secondary"><Icon name="external" size={13} /> Exportar DXF</button>
            <button className="wood-btn wood-btn-primary" onClick={() => setCreating(true)}><Icon name="plus" size={13} /> Novo plano</button>
          </>
        }
      />

      <FormModal open={creating} onClose={() => setCreating(false)}
        kicker="NOVO PLANO" title="Novo plano de corte" icon="saw"
        submitLabel="Gerar plano" maxWidth={620}
        footerHint="Após criar o plano, você adiciona a lista de peças. O sistema calcula automaticamente o melhor aproveitamento das chapas.">
        <FormRow label="Título" required>
          <input className="wood-input" placeholder="Ex: Closet master — Cobertura Vieira Souto" />
        </FormRow>
        <FormRow label="Obra vinculada">
          <select className="wood-select">
            <option value="">Sem obra ainda</option>
            {MOCK.projects.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
          </select>
        </FormRow>
        <FormGrid>
          <FormRow label="Material da chapa" required>
            <select className="wood-select">
              <option>MDF Freijó 18mm</option>
              <option>MDF Branco TX 18mm</option>
              <option>MDF Wengue 18mm</option>
              <option>MDF Carvalho Naturale 18mm</option>
              <option>Compensado 15mm</option>
              <option>MDP 18mm</option>
            </select>
          </FormRow>
          <FormRow label="Dimensão da chapa">
            <select className="wood-select">
              <option value="1840x2750">1840 × 2750 mm (padrão)</option>
              <option value="1850x2470">1850 × 2470 mm</option>
              <option value="2100x2800">2100 × 2800 mm</option>
            </select>
          </FormRow>
        </FormGrid>
        <FormGrid>
          <FormRow label="Responsável">
            <select className="wood-select">
              <option>Tiago Carvalho</option>
              <option>Ricardo Tavares</option>
              <option>Marcos Lima</option>
              <option>Eduardo Marques</option>
            </select>
          </FormRow>
          <FormRow label="Margem de corte (mm)">
            <input type="number" className="wood-input" defaultValue={4} min={0} max={20} />
            <div className="text-xs text-4 mt-1">espessura da serra</div>
          </FormRow>
        </FormGrid>
        <FormRow label="Observações">
          <textarea className="wood-textarea" rows={2} placeholder="Particularidades do veio da madeira, peças com orientação obrigatória, etc." />
        </FormRow>
      </FormModal>

      {/* KPIs */}
      <div className="grid grid-cols-4 gap-4 mb-5">
        <MetricCard icon="saw" label="Planos ativos" value={metrics.open} sub={`${plans.length} no total`} accent="amber" delay={0} />
        <MetricCard icon="layers" label="Chapas planejadas" value={metrics.totalSheets} sub="todas as obras" accent="info" delay={60} />
        <MetricCard icon="trend-up" label="Aproveitamento médio" value={`${metrics.avgUsage.toFixed(1)}%`} sub="por chapa" accent="success" delay={120} />
        <MetricCard icon="dollar" label="Economia estimada" value={`+${metrics.savingPct.toFixed(1)}%`} sub="vs. corte sem plano" accent="success" trend={metrics.savingPct} 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(CUT_STATUS_META).map(([k, m]) => {
          const c = counts[k] || 0;
          if (c === 0) return null;
          return <FilterChip key={k} active={status === k} onClick={() => setStatus(k)} count={c}>{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 título, obra ou material…"
            value={q}
            onChange={e => setQ(e.target.value)}
          />
        </div>
      </div>

      {/* Plan cards (one preview per plan) */}
      {filtered.length === 0 ? (
        <EmptyState icon="saw" title="Nenhum plano" description="Ajuste os filtros ou crie um novo plano de corte." />
      ) : (
        <div className="grid grid-cols-2 gap-5">
          {filtered.map((p, i) => <PlanCard key={p.id} plan={p} delay={i * 60} onOpen={() => setDrawer(p)} />)}
        </div>
      )}

      <PremiumDrawer
        open={!!drawer}
        onClose={() => setDrawer(null)}
        title={drawer?.title}
        subtitle={drawer?.id}
        width={820}
        actions={
          <>
            <button className="wood-btn wood-btn-ghost"><Icon name="external" size={13} /> Exportar DXF</button>
            <button className="wood-btn wood-btn-ghost"><Icon name="file-text" size={13} /> Imprimir OS</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="check" size={13} /> Aprovar plano</button>}
            {drawer?.status === "aprovado" && <button className="wood-btn wood-btn-primary"><Icon name="saw" size={13} /> Iniciar corte</button>}
          </>
        }
      >
        {drawer && <PlanDetail plan={drawer} />}
      </PremiumDrawer>
    </>
  );
};

/* ============================================================
   PlanCard — card with preview of first sheet
   ============================================================ */
const PlanCard = ({ plan, delay, onOpen }) => {
  const totals = planTotals(plan);
  const firstSheet = plan.sheets[0];
  const st = CUT_STATUS_META[plan.status] || CUT_STATUS_META.rascunho;

  return (
    <div className="wood-card wood-card-hover slide-up cursor-pointer overflow-hidden" style={{ animationDelay: `${delay}ms`, padding: 0 }} onClick={onOpen}>
      <div className="p-5 pb-3">
        <div className="flex items-start justify-between gap-3 mb-1">
          <div className="min-w-0">
            <div className="text-md font-semibold tracking-tight text-balance">{plan.title}</div>
            <div className="text-xs text-3 mt-1">{plan.projectName || "Sem obra vinculada"}</div>
          </div>
          <span className="wood-badge flex-shrink-0" style={{ background: st.bg, color: st.fg }}>
            <Icon name={st.icon} size={10} /> {st.label}
          </span>
        </div>

        <div className="grid grid-cols-4 gap-2 mt-4">
          <MiniStat label="Chapas" value={totals.sheets} />
          <MiniStat label="Peças" value={totals.pieces} />
          <MiniStat label="Aproveit." value={`${totals.avgUsage.toFixed(0)}%`} accent />
          <MiniStat label="Material" value={plan.material.split(" ")[0]} muted />
        </div>
      </div>

      {/* Preview do primeiro sheet */}
      <div className="px-5 pb-5">
        <div className="rounded-lg overflow-hidden" style={{ border: "1px solid var(--wood-border-soft)" }}>
          <SheetPreview sheet={firstSheet} sheetSize={plan.sheetSize} aspect={0.55} compact />
        </div>
        {plan.sheets.length > 1 && (
          <div className="text-xs text-3 mt-2 text-center">
            <Icon name="layers" size={11} className="inline-block" style={{ verticalAlign: "middle", marginRight: 4 }} />
            + {plan.sheets.length - 1} {plan.sheets.length === 2 ? "outra chapa" : "outras chapas"}
          </div>
        )}
      </div>
    </div>
  );
};

const MiniStat = ({ label, value, accent, muted }) => (
  <div>
    <div className="text-xs text-4 uppercase tracking-widest" style={{ fontWeight: 500, fontSize: 9.5 }}>{label}</div>
    <div className="text-md font-semibold tracking-tight" style={{
      fontVariantNumeric: "tabular-nums",
      color: accent ? "var(--amber-bright)" : muted ? "var(--text-3)" : "var(--text)"
    }}>{value}</div>
  </div>
);

/* ============================================================
   SheetPreview — 2D visualization of a single sheet
   ============================================================ */
const SheetPreview = ({ sheet, sheetSize, aspect = 0.65, compact = false, big = false }) => {
  const ratio = sheetSize.w / sheetSize.h;
  // SVG viewBox uses real mm
  const viewW = sheetSize.w;
  const viewH = sheetSize.h;

  return (
    <div style={{
      position: "relative",
      width: "100%",
      aspectRatio: `${ratio} / 1`,
      background: "rgba(255,255,255,0.025)",
      overflow: "hidden"
    }}>
      <svg viewBox={`0 0 ${viewW} ${viewH}`} preserveAspectRatio="xMidYMid meet" style={{ width: "100%", height: "100%", display: "block" }}>
        {/* Sheet background grid */}
        <defs>
          <pattern id={`grid-${sheet.id}-${compact ? "c" : "f"}`} width="200" height="200" patternUnits="userSpaceOnUse">
            <path d="M 200 0 L 0 0 0 200" fill="none" stroke="rgba(255,255,255,0.04)" strokeWidth="1" />
          </pattern>
        </defs>
        <rect x="0" y="0" width={viewW} height={viewH} fill={`url(#grid-${sheet.id}-${compact ? "c" : "f"})`} stroke="rgba(255,255,255,0.18)" strokeWidth="6" />

        {/* Pieces */}
        {sheet.pieces.map((p, i) => {
          const color = pieceColor(i);
          const showLabel = big || (p.w * p.h > 200000);
          return (
            <g key={i}>
              <rect
                x={p.x} y={p.y} width={p.w} height={p.h}
                fill={`${color}33`}
                stroke={color}
                strokeWidth="4"
              />
              {showLabel && !compact && (
                <>
                  <text x={p.x + p.w / 2} y={p.y + p.h / 2 - 16} textAnchor="middle" fill={color} fontSize="56" fontWeight="700" style={{ fontFamily: "ui-monospace, monospace" }}>{p.ref}</text>
                  <text x={p.x + p.w / 2} y={p.y + p.h / 2 + 44} textAnchor="middle" fill="rgba(255,255,255,0.78)" fontSize="38" fontWeight="500">{p.label}</text>
                  <text x={p.x + p.w / 2} y={p.y + p.h / 2 + 88} textAnchor="middle" fill="rgba(255,255,255,0.45)" fontSize="34" fontFamily="ui-monospace, monospace">{p.w}×{p.h}</text>
                </>
              )}
              {compact && p.w * p.h > 200000 && (
                <text x={p.x + p.w / 2} y={p.y + p.h / 2 + 18} textAnchor="middle" fill={color} fontSize="80" fontWeight="700" style={{ fontFamily: "ui-monospace, monospace" }}>{p.ref}</text>
              )}
            </g>
          );
        })}

        {/* Sheet dimensions */}
        <text x={viewW / 2} y={viewH - 14} textAnchor="middle" fill="rgba(255,255,255,0.35)" fontSize="36" fontFamily="ui-monospace, monospace">
          {viewW}mm × {viewH}mm
        </text>
      </svg>
    </div>
  );
};

/* ============================================================
   PlanDetail — drawer content with all sheets
   ============================================================ */
const PlanDetail = ({ plan }) => {
  const [activeSheet, setActiveSheet] = useStateCut(0);
  const totals = planTotals(plan);
  const sheet = plan.sheets[activeSheet];
  const st = CUT_STATUS_META[plan.status];

  return (
    <div>
      {/* Summary */}
      <div className="wood-card wood-veneer p-5 mb-5">
        <div className="grid grid-cols-5 gap-3">
          <div>
            <div className="text-xs text-4 uppercase tracking-widest mb-1" style={{ fontWeight: 500 }}>OBRA</div>
            <div className="text-sm" style={{ fontWeight: 600 }}>{plan.projectName || "—"}</div>
          </div>
          <div>
            <div className="text-xs text-4 uppercase tracking-widest mb-1" style={{ fontWeight: 500 }}>MATERIAL</div>
            <div className="text-sm" style={{ fontWeight: 600 }}>{plan.material}</div>
          </div>
          <div>
            <div className="text-xs text-4 uppercase tracking-widest mb-1" style={{ fontWeight: 500 }}>CHAPAS</div>
            <div className="text-md font-semibold tracking-tight">{totals.sheets} × {plan.sheetSize.w}/{plan.sheetSize.h}mm</div>
          </div>
          <div>
            <div className="text-xs text-4 uppercase tracking-widest mb-1" style={{ fontWeight: 500 }}>PEÇAS</div>
            <div className="text-md font-semibold tracking-tight">{totals.pieces} no total</div>
          </div>
          <div>
            <div className="text-xs text-amber uppercase tracking-widest mb-1" style={{ fontWeight: 600 }}>APROVEIT.</div>
            <div className="text-xl font-semibold tracking-tight wood-gradient-text" style={{ fontVariantNumeric: "tabular-nums" }}>{totals.avgUsage.toFixed(1)}%</div>
          </div>
        </div>
      </div>

      {/* Sheet tabs */}
      <div className="flex items-center gap-2 mb-3 overflow-x-auto" style={{ paddingBottom: 4 }}>
        {plan.sheets.map((s, i) => (
          <button key={s.id} onClick={() => setActiveSheet(i)}
            className="px-3 py-2 rounded-lg flex items-center gap-2 flex-shrink-0"
            style={{
              background: activeSheet === i ? "rgba(16,185,129,0.14)" : "var(--wood-surface-2)",
              border: `1px solid ${activeSheet === i ? "rgba(16,185,129,0.45)" : "var(--wood-border)"}`,
              color: activeSheet === i ? "var(--amber-bright)" : "var(--text-2)",
              cursor: "pointer", fontSize: 13,
              fontWeight: activeSheet === i ? 600 : 500
            }}>
            <Icon name="layers" size={12} /> Chapa {i + 1}
            <span className="text-xs" style={{ color: activeSheet === i ? "var(--amber-bright)" : "var(--text-4)", fontVariantNumeric: "tabular-nums" }}>{s.usage.toFixed(0)}%</span>
          </button>
        ))}
      </div>

      {/* Active sheet visualization */}
      <div className="wood-card mb-4 overflow-hidden" style={{ padding: 0 }}>
        <div className="flex items-center justify-between p-3" style={{ background: "rgba(0,0,0,0.32)", borderBottom: "1px solid var(--wood-border-soft)" }}>
          <div className="text-sm" style={{ fontWeight: 600 }}>Chapa {activeSheet + 1} — {sheet.pieces.length} peças</div>
          <div className="flex items-center gap-3 text-xs">
            <span className="text-3">Aproveitamento</span>
            <span className="wood-badge" style={{
              background: sheet.usage > 85 ? "rgba(34,197,94,0.14)" : sheet.usage > 75 ? "rgba(245,158,11,0.14)" : "rgba(239,68,68,0.14)",
              color: sheet.usage > 85 ? "#22C55E" : sheet.usage > 75 ? "#F59E0B" : "#EF4444",
              padding: "2px 8px", fontVariantNumeric: "tabular-nums", fontWeight: 600
            }}>{sheet.usage.toFixed(1)}%</span>
          </div>
        </div>
        <SheetPreview sheet={sheet} sheetSize={plan.sheetSize} big />
      </div>

      {/* Pieces table */}
      <div className="text-sm font-semibold mb-2">Lista de peças desta chapa</div>
      <div className="wood-card overflow-hidden" style={{ padding: 0 }}>
        <table className="wood-table">
          <thead>
            <tr>
              <th style={{ width: 50 }}>Cor</th>
              <th>Ref.</th>
              <th>Peça</th>
              <th>Dimensões</th>
              <th>Posição</th>
              <th>Área</th>
            </tr>
          </thead>
          <tbody>
            {sheet.pieces.map((p, i) => {
              const color = pieceColor(i);
              const area = (p.w * p.h) / 1000000; // m²
              return (
                <tr key={i}>
                  <td>
                    <div style={{ width: 14, height: 14, borderRadius: 3, background: `${color}33`, border: `2px solid ${color}` }} />
                  </td>
                  <td className="font-mono text-xs" style={{ color, fontWeight: 700 }}>{p.ref}</td>
                  <td className="text-sm">{p.label}</td>
                  <td className="text-sm" style={{ fontVariantNumeric: "tabular-nums" }}>{p.w} × {p.h} mm</td>
                  <td className="text-xs text-3" style={{ fontVariantNumeric: "tabular-nums", fontFamily: "ui-monospace, monospace" }}>x={p.x}, y={p.y}</td>
                  <td className="text-sm" style={{ fontVariantNumeric: "tabular-nums" }}>{area.toFixed(3)} m²</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
};

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