// Dashboard + New Analysis modal + Buy Credits modal.

// ─── Dashboard ────────────────────────────────────────────────────────────────
function Dashboard({ usage, analyses, onOpenNew, onOpenBuy, onOpenAnalise }) {
  const last30 = useMemo(() => {
    const m = { COMPLETE: 0, INPROGRESS: 0, FAILED: 0 };
    const cutoff = Date.now() - 30 * 86400000;
    for (const a of analyses) {
      if (new Date(a.created_at).getTime() < cutoff) continue;
      if (a.status === 'COMPLETE') m.COMPLETE++;
      else if (a.status === 'FAILED') m.FAILED++;
      else m.INPROGRESS++;
    }
    return m;
  }, [analyses]);

  const recents = analyses.slice(0, 10);
  const lowBalance = usage.credit_balance < 3;

  return (
    <div className="px-4 sm:px-8 py-5 sm:py-7 max-w-[1280px] mx-auto">
      {/* Low balance banner */}
      {lowBalance && (
        <div className="mb-6 rounded-md border border-warn-200 bg-warn-50 px-4 py-3 flex items-start gap-3 fade-in">
          <span className="mt-0.5 text-warn-700"><Icon.Alert /></span>
          <div className="flex-1">
            <div className="text-[13.5px] font-semibold text-warn-700">Saldo baixo — recarregue antes do próximo prazo.</div>
            <div className="text-[12.5px] text-warn-700/90 mt-0.5">Restam apenas {usage.credit_balance} créditos. Pagamento por PIX é instantâneo.</div>
          </div>
          <Button variant="primary" size="sm" onClick={onOpenBuy}>Comprar créditos</Button>
        </div>
      )}

      {/* Credit card hero */}
      <div className="rounded-lg bg-white border border-ink-200 shadow-card overflow-hidden">
        <div className="px-6 py-5 grid grid-cols-1 lg:grid-cols-[1fr_auto] gap-6 items-center">
          <div className="min-w-0">
            <div className="text-[11px] uppercase tracking-tracker text-ink-500 font-medium">
              Saldo de créditos · não expira
            </div>
            <div className="mt-2 flex items-baseline gap-3 tabular">
              <span className="text-[56px] leading-none font-bold text-ink-900 tracking-tightish">{usage.credit_balance}</span>
              <span className="text-[14px] text-ink-500">créditos disponíveis</span>
            </div>

            <div className="mt-3 text-[12px] text-ink-500">
              {usage.last_purchase
                ? <>Última recarga: <span className="text-ink-900 font-semibold tabular">{usage.last_purchase.credits}</span> créditos em <span className="tabular">{fmtDate.format(new Date(usage.last_purchase.at))}</span> · cada análise consome 1 crédito</>
                : <>Cada análise consome 1 crédito · créditos não têm prazo de validade</>}
            </div>
          </div>

          <div className="flex flex-col gap-2 lg:items-end">
            <Button size="lg" onClick={onOpenBuy} className="w-full lg:w-auto">
              <Icon.Coins /> Comprar mais créditos
            </Button>
            {usage.plan_label && (
              <div className="text-[11.5px] text-ink-500 lg:text-right">
                Pacote atual: <span className="font-semibold text-ink-700">{usage.plan_label}</span>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Month stats */}
      <div className="mt-6 grid grid-cols-1 sm:grid-cols-3 gap-4">
        <StatTile
          label="Concluídas no mês"
          value={last30.COMPLETE}
          hint="Artefatos gerados e entregues"
          accent="text-ok-700"
        />
        <StatTile
          label="Em andamento"
          value={last30.INPROGRESS}
          hint="Aguardando processamento ou cálculo"
          accent="text-navy-800"
        />
        <StatTile
          label="Falhas"
          value={last30.FAILED}
          hint="PDFs protegidos, ilegíveis ou erro técnico"
          accent={last30.FAILED > 0 ? 'text-danger-700' : 'text-ink-900'}
        />
      </div>

      {/* Recents table */}
      <section className="mt-8">
        <div className="flex items-end justify-between mb-3">
          <div>
            <h2 className="text-[15px] font-semibold text-ink-900">Análises recentes</h2>
            <p className="text-[12.5px] text-ink-500 mt-0.5">Últimas 10 análises do escritório.</p>
          </div>
          <button className="text-[12.5px] text-navy-800 hover:underline font-medium">Ver tudo</button>
        </div>

        {recents.length === 0 ? (
          <EmptyState onOpenNew={onOpenNew} />
        ) : (
          <div className="bg-white rounded-lg border border-ink-200 overflow-hidden shadow-card">
            <table className="w-full text-[13px]">
              <thead className="bg-ink-50 border-b border-ink-200">
                <tr className="text-left text-[11.5px] uppercase tracking-tracker text-ink-500 font-medium">
                  <th className="px-5 py-2.5">Data</th>
                  <th className="px-5 py-2.5">Requerente</th>
                  <th className="px-5 py-2.5">Tipo</th>
                  <th className="px-5 py-2.5">Status</th>
                  <th className="px-5 py-2.5">Viabilidade</th>
                  <th className="px-5 py-2.5 text-right">ID</th>
                  <th className="px-5 py-2.5 w-0"></th>
                </tr>
              </thead>
              <tbody>
                {recents.map((a) => (
                  <tr
                    key={a.id}
                    onClick={() => onOpenAnalise(a.id)}
                    className="border-b border-ink-100 last:border-0 hover:bg-ink-50 cursor-pointer transition-colors"
                  >
                    <td className="px-5 py-3 text-ink-700 tabular whitespace-nowrap">{fmtDateTime.format(new Date(a.created_at))}</td>
                    <td className="px-5 py-3 text-ink-900 font-medium">{a.requerente_nome || <span className="text-ink-400">—</span>}</td>
                    <td className="px-5 py-3 text-ink-700">
                      <span className="inline-flex items-center gap-1.5">
                        Revisional Veículo
                        <span className="text-ink-400 font-mono text-[11px]">{a.pericia_version_label}</span>
                      </span>
                    </td>
                    <td className="px-5 py-3"><StatusBadge status={a.status} /></td>
                    <td className="px-5 py-3"><ViabilityChip value={a.viability_result} /></td>
                    <td className="px-5 py-3 text-right font-mono text-[11.5px] text-ink-500">#{shortId(a.id)}</td>
                    <td className="px-5 py-3 text-ink-400"><Icon.ArrowR /></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </section>
    </div>
  );
}

function EmptyState({ onOpenNew }) {
  return (
    <div className="bg-white rounded-lg border border-ink-200 px-6 py-14 text-center shadow-card">
      <div className="mx-auto w-12 h-12 rounded-full bg-navy-50 text-navy-800 flex items-center justify-center mb-4">
        <Icon.Doc />
      </div>
      <h3 className="text-[15px] font-semibold text-ink-900">Nenhuma análise ainda</h3>
      <p className="mt-1 text-[13px] text-ink-500 max-w-md mx-auto">
        Envie seu primeiro contrato em PDF para gerar planilha, painel e memória de cálculo.
      </p>
      <div className="mt-5">
        <Button onClick={onOpenNew}><Icon.Plus /> Criar primeira análise</Button>
      </div>
    </div>
  );
}

// ─── New Analysis Modal ───────────────────────────────────────────────────────
function NewAnalysisModal({ open, onClose, usage, periciaTypes, onSubmit }) {
  const [file, setFile]       = useState(null);
  const [tipo, setTipo]       = useState(periciaTypes[0]?.code || '');
  const [requerente, setReq]  = useState('');
  const [dragOver, setDragOver] = useState(false);
  const [error, setError]     = useState(null);
  const [submitting, setSubmitting] = useState(false);
  const inputRef = useRef(null);

  useEffect(() => {
    if (open) { setFile(null); setReq(''); setError(null); setDragOver(false); }
  }, [open]);

  const sufficient = usage.credit_balance > 0;
  const idempKey = useMemo(() => uuid(), [open]);

  const acceptFile = (f) => {
    setError(null);
    if (!f) return;
    if (f.type && f.type !== 'application/pdf' && !f.name.toLowerCase().endsWith('.pdf')) {
      setError('Apenas arquivos PDF são aceitos. Converta antes de enviar.');
      return;
    }
    if (f.size > 50 * 1024 * 1024) {
      setError('Arquivo excede o limite de 50 MB. Reduza ou divida o PDF.');
      return;
    }
    setFile(f);
  };

  const submit = () => {
    if (!file || !sufficient || submitting) return;
    setSubmitting(true);
    setTimeout(() => {
      onSubmit({
        file,
        pericia_type_code: tipo,
        requerente_nome: requerente.trim() || null,
        idempotency_key: idempKey,
      });
      setSubmitting(false);
    }, 600);
  };

  const fmtBytes = (n) => {
    if (n < 1024) return `${n} B`;
    if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
    return `${(n / 1024 / 1024).toFixed(2)} MB`;
  };

  return (
    <Modal open={open} onClose={onClose} width="max-w-xl" label="Nova análise">
      <ModalHeader
        title="Nova análise pericial"
        subtitle="Envie o contrato em PDF e selecione o tipo de perícia."
        onClose={onClose}
      />

      <div className="px-6 py-5 overflow-y-auto flex-1 space-y-5">
        {/* Dropzone */}
        <div
          onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}
          onDragLeave={() => setDragOver(false)}
          onDrop={(e) => { e.preventDefault(); setDragOver(false); acceptFile(e.dataTransfer.files?.[0]); }}
          onClick={() => inputRef.current?.click()}
          className={`relative border-2 border-dashed rounded-lg px-5 py-8 text-center cursor-pointer transition-colors ${
            dragOver
              ? 'border-navy-800 bg-navy-50'
              : file
                ? 'border-ok-200 bg-ok-50/50'
                : 'border-ink-200 bg-ink-50/60 hover:border-navy-800/40 hover:bg-navy-50/40'
          }`}
        >
          <input
            ref={inputRef}
            type="file"
            accept="application/pdf,.pdf"
            className="hidden"
            onChange={(e) => acceptFile(e.target.files?.[0])}
          />
          {file ? (
            <div className="flex items-center justify-center gap-4">
              <div className="text-ok-700"><Icon.Pdf /></div>
              <div className="text-left">
                <div className="text-[13.5px] font-semibold text-ink-900 truncate max-w-[320px]">{file.name}</div>
                <div className="text-[12px] text-ink-500 tabular">{fmtBytes(file.size)} · PDF</div>
              </div>
              <button
                onClick={(e) => { e.stopPropagation(); setFile(null); }}
                className="ml-2 text-ink-400 hover:text-ink-900"
                aria-label="Remover arquivo"
              >
                <Icon.X />
              </button>
            </div>
          ) : (
            <div className="text-ink-500">
              <div className="mx-auto w-10 h-10 rounded-full bg-white border border-ink-200 flex items-center justify-center text-navy-800 mb-2">
                <Icon.Upload />
              </div>
              <div className="text-[13.5px] text-ink-900 font-medium">
                Arraste o PDF do contrato ou <span className="text-navy-800 underline underline-offset-2">selecione</span>
              </div>
              <div className="text-[12px] mt-1">PDF até 50 MB · texto extraível preferencial</div>
            </div>
          )}
        </div>

        {error && (
          <div className="rounded-md border border-danger-200 bg-danger-50 px-3 py-2 text-[12.5px] text-danger-700 flex items-start gap-2">
            <span className="mt-0.5"><Icon.Alert /></span><span>{error}</span>
          </div>
        )}

        <Field label="Tipo de perícia">
          <Select value={tipo} onChange={(e) => setTipo(e.target.value)}>
            {periciaTypes.map((p) => (
              <option key={p.code} value={p.code}>
                {p.label} ({p.active_version_label})
              </option>
            ))}
          </Select>
        </Field>

        <Field label="Nome do requerente" hint="Opcional. Aparece no painel de viabilidade e no nome dos artefatos.">
          <TextInput
            placeholder="Nome completo do cliente"
            value={requerente}
            onChange={(e) => setReq(e.target.value)}
          />
        </Field>

        {/* Quota notice */}
        <div className={`rounded-md border px-3.5 py-3 flex items-start gap-3 ${
          sufficient ? 'border-ink-200 bg-ink-50' : 'border-danger-200 bg-danger-50'
        }`}>
          <span className={`mt-0.5 ${sufficient ? 'text-navy-800' : 'text-danger-700'}`}>
            {sufficient ? <Icon.Info /> : <Icon.Alert />}
          </span>
          {sufficient ? (
            <div className="text-[12.5px] text-ink-700 leading-snug">
              Esta análise consumirá <span className="font-semibold text-ink-900">1 crédito</span>. Saldo atual:
              {' '}<span className="font-semibold text-ink-900 tabular">{usage.credit_balance}</span> → ficará
              {' '}<span className="font-semibold text-ink-900 tabular">{usage.credit_balance - 1}</span>.
            </div>
          ) : (
            <div className="text-[12.5px] text-danger-700 leading-snug">
              <span className="font-semibold">Saldo zerado.</span> Compre créditos antes de enviar uma nova análise.
            </div>
          )}
        </div>

        <div className="text-[11px] uppercase tracking-tracker text-ink-400 font-mono flex items-center gap-2">
          <span>Idempotency-Key</span>
          <span className="text-ink-500">{idempKey}</span>
        </div>
      </div>

      <div className="px-6 py-4 border-t border-ink-200 flex items-center justify-end gap-2 bg-ink-50/60">
        <Button variant="ghost" onClick={onClose} disabled={submitting}>Cancelar</Button>
        {!sufficient ? (
          <Button variant="primary" onClick={() => { onClose(); /* parent opens buy */ window.dispatchEvent(new CustomEvent('open-buy')); }}>
            Comprar créditos primeiro
          </Button>
        ) : (
          <Button onClick={submit} disabled={!file || submitting}>
            {submitting ? <><Spinner color="#fff" /> Enviando…</> : <>Enviar análise <Icon.ArrowR /></>}
          </Button>
        )}
      </div>
    </Modal>
  );
}

// ─── Buy Credits Modal ────────────────────────────────────────────────────────
function BuyCreditsModal({ open, onClose, onPurchase }) {
  const [picked, setPicked] = useState('p100');
  const [method, setMethod] = useState('pix');
  const packages = [
    { id: 'p20',  credits: 20,  price: 197.00,  unit: 9.85,  highlight: null,           extra: null },
    { id: 'p100', credits: 100, price: 697.00,  unit: 6.97,  highlight: 'Mais popular', extra: null },
    { id: 'p500', credits: 500, price: 2497.00, unit: 4.99,  highlight: null,           extra: 'Prioridade na fila' },
  ];
  const methods = [
    { id: 'pix',     label: 'PIX',          time: 'Instantâneo',     tag: 'Recomendado' },
    { id: 'cartao',  label: 'Cartão',       time: 'Recorrente mensal' },
  ];
  const selected = packages.find((p) => p.id === picked);

  return (
    <Modal open={open} onClose={onClose} width="max-w-3xl" label="Comprar créditos">
      <ModalHeader
        title="Comprar créditos"
        subtitle="Créditos não expiram. Cada análise consome 1 crédito."
        onClose={onClose}
      />
      <div className="px-6 py-5 overflow-y-auto flex-1">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
          {packages.map((p) => {
            const active = p.id === picked;
            return (
              <button
                key={p.id}
                onClick={() => setPicked(p.id)}
                className={`relative text-left rounded-lg border px-5 py-4 transition-all ${
                  active
                    ? 'border-navy-800 bg-navy-50/40 shadow-cardHover'
                    : 'border-ink-200 bg-white hover:border-ink-300'
                }`}
              >
                {p.highlight && (
                  <span className="absolute -top-2.5 left-4 text-[10.5px] uppercase tracking-tracker font-bold bg-navy-800 text-white px-2 py-0.5 rounded">
                    {p.highlight}
                  </span>
                )}
                <div className="flex items-baseline gap-1 tabular">
                  <span className="text-[34px] leading-none font-bold text-ink-900">{p.credits}</span>
                  <span className="text-[13px] text-ink-500">créditos</span>
                </div>
                <div className="mt-3 text-[18px] font-semibold text-ink-900 tabular">{fmtBRL.format(p.price)}</div>
                <div className="text-[11.5px] text-ink-500 tabular">{fmtBRL.format(p.unit)} / análise</div>
                {p.extra && (
                  <div className="mt-3 inline-flex items-center gap-1.5 text-[11.5px] text-navy-800 font-medium">
                    <Icon.Check /> {p.extra}
                  </div>
                )}
                <div className={`mt-3 h-1 rounded-full ${active ? 'bg-navy-800' : 'bg-ink-100'}`} />
              </button>
            );
          })}
        </div>

        <div className="mt-6">
          <div className="text-[12px] uppercase tracking-tracker text-ink-500 font-medium mb-2">Método de pagamento</div>
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-2.5">
            {methods.map((m) => {
              const active = method === m.id;
              return (
                <button
                  key={m.id}
                  onClick={() => setMethod(m.id)}
                  className={`text-left rounded-md border px-3.5 py-3 transition-colors ${
                    active ? 'border-navy-800 bg-navy-50/60' : 'border-ink-200 bg-white hover:border-ink-300'
                  }`}
                >
                  <div className="flex items-center justify-between">
                    <span className="text-[13.5px] font-semibold text-ink-900">{m.label}</span>
                    {m.tag && <span className="text-[10px] uppercase tracking-tracker text-navy-800 font-bold">{m.tag}</span>}
                  </div>
                  <div className="text-[11.5px] text-ink-500 mt-0.5">{m.time}</div>
                </button>
              );
            })}
          </div>
        </div>

        <div className="mt-6 rounded-md bg-ink-50 border border-ink-200 px-4 py-3 flex items-center justify-between">
          <div className="text-[12.5px] text-ink-500">
            Resumo: <span className="text-ink-900 font-medium">{selected.credits} créditos</span> · <span className="capitalize">{method}</span>
          </div>
          <div className="text-[16px] font-bold text-ink-900 tabular">{fmtBRL.format(selected.price)}</div>
        </div>
      </div>

      <div className="px-6 py-4 border-t border-ink-200 flex items-center justify-between bg-ink-50/60">
        <div className="text-[11.5px] text-ink-500">Nota fiscal eletrônica emitida em até 24h após pagamento.</div>
        <div className="flex items-center gap-2">
          <Button variant="ghost" onClick={onClose}>Cancelar</Button>
          <Button onClick={() => onPurchase(selected, method)}>
            Continuar pagamento <Icon.ArrowR />
          </Button>
        </div>
      </div>
    </Modal>
  );
}

// Modal de senha pra PDF protegido: o backend devolveu 422 PDF_PASSWORD_REQUIRED
// e o submit original foi suspenso. Aqui o usuário digita a senha e a UI retenta
// o mesmo upload via onSubmit (que repassa pra submitNewAnalysis(bundle, {pdf_password})).
function PdfPasswordModal({ open, prompt, onClose, onSubmit }) {
  const [password, setPassword] = useState('');
  const [submitting, setSubmitting] = useState(false);

  useEffect(() => {
    if (open) { setPassword(''); setSubmitting(false); }
  }, [open, prompt]);

  if (!open || !prompt) return null;

  const submit = (e) => {
    e?.preventDefault?.();
    if (!password.trim() || submitting) return;
    setSubmitting(true);
    onSubmit(prompt.bundle, { pdf_password: password });
  };

  const fileName = prompt.bundle?.file?.name || 'contrato.pdf';

  return (
    <Modal open={open} onClose={onClose} title="PDF protegido por senha" width="w-[440px]">
      <form onSubmit={submit}>
        <p className="text-[13px] text-ink-700 leading-snug">
          O arquivo <span className="font-medium text-ink-900">{fileName}</span> está protegido por senha.
          Informe a senha para que possamos abrir o PDF e processar a análise.
        </p>
        <p className="mt-2 text-[12px] text-ink-500 leading-snug">
          A senha é usada apenas para abrir o documento neste momento — ela não fica armazenada.
        </p>
        <div className="mt-5">
          <label className="block text-[12.5px] font-medium text-ink-700 mb-1.5">Senha do PDF</label>
          <input
            type="password"
            autoFocus
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            placeholder="Digite a senha"
            className="w-full px-3 py-2.5 text-[14px] border border-ink-200 rounded-md focus:border-navy-800 focus:ring-1 focus:ring-navy-800/20"
          />
          {prompt.error && (
            <div className="mt-2 text-[12.5px] text-danger-700">{prompt.error}</div>
          )}
        </div>
        <div className="mt-6 flex items-center justify-end gap-2.5">
          <Button variant="ghost" onClick={onClose} type="button">Cancelar</Button>
          <Button variant="primary" type="submit" disabled={!password.trim() || submitting}>
            {submitting ? 'Validando…' : 'Continuar'}
          </Button>
        </div>
      </form>
    </Modal>
  );
}

Object.assign(window, { Dashboard, NewAnalysisModal, BuyCreditsModal, PdfPasswordModal });
