// Modals and secondary views (full list, debts page)

const { useState: useStateM, useEffect: useEffectM, useRef: useRefM } = React;

// ---------- MODAL SHELL ----------
function Modal({ title, onClose, children, footer }) {
  const backDown = useRefM(false);
  useEffectM(() => {
    const onKey = e => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onClose]);

  return (
    <div className="modal-back"
      onMouseDown={e => { backDown.current = e.target === e.currentTarget; }}
      onMouseUp={e => { if (backDown.current && e.target === e.currentTarget) onClose(); backDown.current = false; }}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="modal-head">
          <h3>{title}</h3>
          <button className="modal-x" onClick={onClose}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M18 6L6 18M6 6l12 12"/></svg>
          </button>
        </div>
        <div className="modal-body">{children}</div>
        {footer && <div className="modal-foot">{footer}</div>}
      </div>
    </div>
  );
}

// ---------- ADD TX MODAL ----------
function AddTxModal({ kind, onClose, onSave, categorias, contas, defaultMonth, defaultYear }) {
  const isIncome = kind === "receita";
  const today = new Date();
  const defaultDate = `${defaultYear}-${String(defaultMonth + 1).padStart(2, "0")}-${String(today.getDate()).padStart(2, "0")}`;

  const [form, setForm] = useStateM({
    description: "",
    date: defaultDate,
    amount: "",
    account: contas[0] || "PIX",
    category: isIncome ? "💸 Receita" : (categorias.find(c => c.tipo !== "Receita")?.nome || "🤷 Outros"),
    status: "Pago",
    redutivel: false,
    fixa: false,
    classe: "variavel",
  });

  const cats = isIncome
    ? categorias.filter(c => c.tipo === "Receita")
    : categorias.filter(c => c.tipo !== "Receita");

  function submit(e) {
    e.preventDefault();
    const amount = window.parseValor(form.amount);
    if (!form.description || isNaN(amount) || amount <= 0) return;
    onSave({
      id: window.uid(),
      description: form.description,
      date: form.date,
      amount: amount,
      account: form.account,
      category: form.category,
      type: isIncome ? "Receita" : "Despesa",
      status: form.status,
      redutivel: isIncome ? false : form.redutivel,
      fixa: form.fixa,
      classe: isIncome ? undefined : form.classe,
    });
    onClose();
  }

  const title = isIncome ? "Nova Receita" : "Novo Gasto";

  return (
    <Modal title={title} onClose={onClose}>
      <form className="form" onSubmit={submit}>
        <div className="field">
          <label>Descrição</label>
          <input value={form.description} onChange={e => setForm({...form, description: e.target.value})} placeholder={isIncome ? "Ex: Salário" : "Ex: Mercado"} autoFocus required/>
        </div>
        <div className="form-row">
          <div className="field">
            <label>Valor (R$)</label>
            <input inputMode="decimal" value={form.amount} onChange={e => setForm({...form, amount: e.target.value})} placeholder="0,00" required/>
          </div>
          <div className="field">
            <label>Data</label>
            <input type="date" value={form.date} onChange={e => setForm({...form, date: e.target.value})} required/>
          </div>
        </div>
        <div className="form-row">
          <div className="field">
            <label>Categoria</label>
            <select value={form.category} onChange={e => setForm({...form, category: e.target.value})}>
              {cats.map(c => <option key={c.nome} value={c.nome}>{c.nome}</option>)}
            </select>
          </div>
          <div className="field">
            <label>Conta</label>
            <select value={form.account} onChange={e => setForm({...form, account: e.target.value})}>
              {contas.map(c => <option key={c} value={c}>{c}</option>)}
            </select>
          </div>
        </div>
        <div className="form-row">
          <div className="field">
            <label>Status</label>
            <select value={form.status} onChange={e => setForm({...form, status: e.target.value})}>
              <option>Pago</option>
              <option>Pendente</option>
            </select>
          </div>
          {isIncome ? (
            <div className="field check">
              <label>
                <input type="checkbox" checked={form.fixa} onChange={e => setForm({...form, fixa: e.target.checked})}/>
                <span>Lançamento fixo</span>
              </label>
            </div>
          ) : (
            <div className="field">
              <label>Pode ser reduzido?</label>
              <select value={form.redutivel ? "sim" : "nao"} onChange={e => setForm({...form, redutivel: e.target.value === "sim"})}>
                <option value="nao">Não — essencial / fixo</option>
                <option value="sim">Sim — pode cortar</option>
              </select>
            </div>
          )}
        </div>
        {!isIncome && (
          <div className="form-row">
            <div className="field">
              <label>Classe do gasto</label>
              <select value={form.classe} onChange={e => setForm({...form, classe: e.target.value})}>
                {window.CLASSES.map(c => <option key={c.id} value={c.id}>{c.icon} {c.label}</option>)}
              </select>
            </div>
            <div className="field check" style={{alignSelf: "end"}}>
              <label>
                <input type="checkbox" checked={form.fixa} onChange={e => setForm({...form, fixa: e.target.checked})}/>
                <span>Lançamento fixo</span>
              </label>
            </div>
          </div>
        )}
        <div className="form-actions">
          <button type="button" className="btn-ghost" onClick={onClose}>Cancelar</button>
          <button type="submit" className="btn-green">Salvar lançamento</button>
        </div>
      </form>
    </Modal>
  );
}

// ---------- ADD DEBT MODAL ----------
function AddDebtModal({ onClose, onSave, edit }) {
  const [form, setForm] = useStateM(edit || {
    descricao: "",
    credor: "",
    valorInicial: "",
    saldoDevedor: "",
    dataInicio: new Date().toISOString().slice(0, 10),
    vencimento: "",
    parcelas: 1,
    parcelasPagas: 0,
    status: "Em aberto",
  });

  function submit(e) {
    e.preventDefault();
    const vi = window.parseValor(form.valorInicial);
    const sd = window.parseValor(form.saldoDevedor);
    onSave({
      id: edit?.id || ("d" + window.uid()),
      descricao: form.descricao,
      credor: form.credor,
      valorInicial: isNaN(vi) ? 0 : vi,
      saldoDevedor: isNaN(sd) ? (isNaN(vi) ? 0 : vi) : sd,
      dataInicio: form.dataInicio,
      vencimento: form.vencimento,
      parcelas: Number(form.parcelas),
      parcelasPagas: Number(form.parcelasPagas),
      status: form.status,
    });
    onClose();
  }

  return (
    <Modal title={edit ? "Editar Dívida" : "Nova Dívida"} onClose={onClose}>
      <form className="form" onSubmit={submit}>
        <div className="form-row">
          <div className="field">
            <label>Descrição</label>
            <input value={form.descricao} onChange={e => setForm({...form, descricao: e.target.value})} required autoFocus/>
          </div>
          <div className="field">
            <label>Credor</label>
            <input value={form.credor} onChange={e => setForm({...form, credor: e.target.value})}/>
          </div>
        </div>
        <div className="form-row">
          <div className="field">
            <label>Valor Inicial (R$)</label>
            <input inputMode="decimal" value={form.valorInicial} onChange={e => setForm({...form, valorInicial: e.target.value, saldoDevedor: form.saldoDevedor || e.target.value})} required/>
          </div>
          <div className="field">
            <label>Saldo Devedor (R$)</label>
            <input inputMode="decimal" value={form.saldoDevedor} onChange={e => setForm({...form, saldoDevedor: e.target.value})}/>
          </div>
        </div>
        <div className="form-row">
          <div className="field">
            <label>Data de Início</label>
            <input type="date" value={form.dataInicio} onChange={e => setForm({...form, dataInicio: e.target.value})}/>
          </div>
          <div className="field">
            <label>Vencimento</label>
            <input type="date" value={form.vencimento} onChange={e => setForm({...form, vencimento: e.target.value})}/>
          </div>
        </div>
        <div className="form-row">
          <div className="field">
            <label>Nº Parcelas</label>
            <input type="number" value={form.parcelas} onChange={e => setForm({...form, parcelas: e.target.value})} min="1"/>
          </div>
          <div className="field">
            <label>Parcelas Pagas</label>
            <input type="number" value={form.parcelasPagas} onChange={e => setForm({...form, parcelasPagas: e.target.value})} min="0"/>
          </div>
        </div>
        <div className="field">
          <label>Status</label>
          <select value={form.status} onChange={e => setForm({...form, status: e.target.value})}>
            <option>Em aberto</option>
            <option>Finalizado</option>
            <option>Sem Negociação</option>
          </select>
        </div>
        <div className="form-actions">
          <button type="button" className="btn-ghost" onClick={onClose}>Cancelar</button>
          <button type="submit" className="btn-green">Salvar dívida</button>
        </div>
      </form>
    </Modal>
  );
}

// ---------- DÍVIDAS PAGE ----------
function DividasPage({ dividas, onAdd, onEdit, onDelete }) {
  const total = dividas.reduce((s, d) => s + d.saldoDevedor, 0);
  const pago = dividas.reduce((s, d) => s + (d.valorInicial - d.saldoDevedor), 0);
  const abertas = dividas.filter(d => d.status === "Em aberto").length;
  const semNeg = dividas.filter(d => d.status === "Sem Negociação").length;
  const finalizadas = dividas.filter(d => d.status === "Finalizado").length;

  return (
    <div className="page">
      <div className="page-head">
        <h2>📋 Rastreador de Dívidas</h2>
        <button className="btn-green" onClick={onAdd}>+ Nova Dívida</button>
      </div>
      <div className="div-summary">
        <div className="ds-card">
          <div className="ds-label">Total de Dívidas</div>
          <Amount value={dividas.reduce((s, d) => s + d.valorInicial, 0)}/>
        </div>
        <div className="ds-card">
          <div className="ds-label">Saldo Devedor</div>
          <Amount value={total}/>
        </div>
        <div className="ds-card">
          <div className="ds-label">Saldo Pago</div>
          <Amount value={pago}/>
        </div>
        <div className="ds-stats">
          <div className="ds-stat"><span>Em aberto</span><strong>{abertas}</strong></div>
          <div className="ds-stat"><span>Sem negociação</span><strong>{semNeg}</strong></div>
          <div className="ds-stat"><span>Finalizadas</span><strong>{finalizadas}</strong></div>
        </div>
      </div>

      <div className="card">
        <table className="div-table">
          <thead>
            <tr>
              <th>Descrição</th>
              <th>Credor</th>
              <th>Valor Inicial</th>
              <th>Saldo Devedor</th>
              <th>Vencimento</th>
              <th>Parcelas</th>
              <th>Status</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {dividas.map(d => {
              const pct = d.valorInicial > 0 ? Math.round(((d.valorInicial - d.saldoDevedor) / d.valorInicial) * 100) : 0;
              return (
                <tr key={d.id}>
                  <td>
                    <div className="dt-name">{d.descricao}</div>
                    <div className="dt-progress">
                      <div className="dt-bar"><div style={{width: pct + "%"}}/></div>
                      <span>{pct}%</span>
                    </div>
                  </td>
                  <td>{d.credor || "—"}</td>
                  <td>{window.fmtBRLString(d.valorInicial)}</td>
                  <td><strong>{window.fmtBRLString(d.saldoDevedor)}</strong></td>
                  <td>{d.vencimento ? d.vencimento.split("-").reverse().join("/") : "—"}</td>
                  <td>{d.parcelasPagas}/{d.parcelas}</td>
                  <td><span className={`badge badge-${d.status === "Em aberto" ? "open" : d.status === "Finalizado" ? "done" : "muted"}`}>{d.status}</span></td>
                  <td>
                    <div className="row-actions">
                      <button onClick={() => onEdit(d)} title="Editar">
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M11 4H4v16h16v-7"/><path d="M18 2l4 4-10 10H8v-4z"/></svg>
                      </button>
                      <button onClick={() => onDelete(d.id)} title="Excluir">
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 6h18M8 6V4a1 1 0 011-1h6a1 1 0 011 1v2M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6"/></svg>
                      </button>
                    </div>
                  </td>
                </tr>
              );
            })}
            {dividas.length === 0 && (
              <tr><td colSpan="8" className="empty-tx">Nenhuma dívida cadastrada.</td></tr>
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ---------- LANÇAMENTOS: ver src/checklist.jsx (checklist mensal) ----------

Object.assign(window, { Modal, AddTxModal, AddDebtModal, DividasPage });
