// Panels: spending overview (donut), AI insight, quick actions, recommendations, transactions, debts

const { useState: useStateP, useMemo: useMemoP } = React;

// ---------- DONUT (SVG) ----------
function Donut({ data, size = 220, thickness = 32 }) {
  const total = data.reduce((s, d) => s + d.value, 0) || 1;
  const r = size / 2 - thickness / 2;
  const cx = size / 2, cy = size / 2;
  const C = 2 * Math.PI * r;

  let offset = 0;
  // shades of green from dark to light to match reference
  const colors = ["#0e4a40", "#177a63", "#2a9d84", "#f0b84d", "#f6cd7c", "#e5d9b8", "#c4d6cf", "#d9e6e0", "#f3eedf"];

  return (
    <div className="donut-wrap">
      <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
        <circle cx={cx} cy={cy} r={r} fill="none" stroke="#f3eedf" strokeWidth={thickness}/>
        {data.map((d, i) => {
          const len = (d.value / total) * C;
          const seg = (
            <circle key={i}
              cx={cx} cy={cy} r={r} fill="none"
              stroke={colors[i % colors.length]}
              strokeWidth={thickness}
              strokeDasharray={`${len} ${C - len}`}
              strokeDashoffset={-offset}
              strokeLinecap="butt"
              transform={`rotate(-90 ${cx} ${cy})`}/>
          );
          offset += len;
          return seg;
        })}
      </svg>
      <div className="donut-center">
        <div className="dc-label">Top Categoria</div>
        <div className="dc-value">{data[0]?.category || "—"}</div>
      </div>
    </div>
  );
}

// ---------- SPENDING OVERVIEW ----------
function SpendingOverview({ catData, total, period, setPeriod, onGoTo }) {
  const colors = ["#0e4a40", "#177a63", "#2a9d84", "#f0b84d", "#f6cd7c", "#e5d9b8", "#c4d6cf", "#d9e6e0", "#f3eedf"];
  const top = catData.slice(0, 6);
  return (
    <div className="card spending-overview clickable" onClick={onGoTo && window.cardNav(() => onGoTo("analise"))} title="Ver Análise completa">
      <div className="card-head">
        <h3>Visão de Gastos</h3>
        <select className="period-select" value={period} onChange={e => setPeriod(e.target.value)}>
          <option value="mes">Este Mês</option>
          <option value="ano">Este Ano</option>
        </select>
      </div>
      <div className="so-body">
        <div className="so-left">
          <div className="so-total-label">Total gasto</div>
          <Amount value={total}/>
          <Donut data={top} size={170} thickness={26}/>
        </div>
        <div className="so-list">
          {top.map((c, i) => {
            const pct = total ? Math.round((c.value / total) * 100) : 0;
            return (
              <div className="cat-row" key={c.category}>
                <span className="cat-swatch" style={{background: colors[i]}}/>
                <span className="cat-name">{c.category}</span>
                <span className="cat-value">{window.fmtBRLString(c.value)}</span>
                <span className="cat-pct">{pct}%</span>
              </div>
            );
          })}
          {top.length === 0 && (
            <div className="empty-cats">Sem despesas neste período.</div>
          )}
        </div>
      </div>
    </div>
  );
}

// ---------- AI INSIGHT ----------
function AIInsight({ catData, monthIncome, monthExpense, monthLabel, onGoTo }) {
  const [insight, setInsight] = useStateP(null);
  const [loading, setLoading] = useStateP(false);

  async function generate() {
    setLoading(true);
    try {
      const top3 = catData.slice(0, 3).map(c => `${c.category}: R$ ${c.value.toFixed(2)}`).join(", ");
      const prompt = `Você é um consultor financeiro. Em PORTUGUÊS, em no máximo 2 frases curtas, analise estes dados de ${monthLabel}:
Receita: R$ ${monthIncome.toFixed(2)}
Despesa: R$ ${monthExpense.toFixed(2)}
Top 3 categorias: ${top3}

Identifique 1 padrão preocupante ou oportunidade e SUGIRA uma ação concreta. Não use cumprimentos. Comece direto.`;
      const res = await window.claude.complete(prompt);
      setInsight(res.trim());
    } catch (e) {
      setInsight("Não consegui gerar agora.");
    } finally {
      setLoading(false);
    }
  }

  // Auto-generate a default insight based on the data
  const defaultInsight = useMemoP(() => {
    if (!catData[0]) return "Adicione lançamentos para receber análises.";
    const top = catData[0];
    const pct = monthExpense ? Math.round((top.value / monthExpense) * 100) : 0;
    if (monthExpense > monthIncome) {
      const deficit = monthExpense - monthIncome;
      return `Seus gastos ultrapassaram a receita em ${window.fmtBRLString(deficit)} neste mês. ${top.category} representa ${pct}% — vale revisar.`;
    }
    return `${top.category} concentra ${pct}% dos seus gastos do mês. Quer dicas para reduzir?`;
  }, [catData, monthIncome, monthExpense]);

  return (
    <div className="card ai-insight clickable" onClick={onGoTo && window.cardNav(() => onGoTo("insights"))} title="Ver Insights">
      <div className="ai-head-row">
        <span className="ai-tag">
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <path d="M12 2L9 9l-7 .5 5.5 4.5L6 22l6-4 6 4-1.5-8L22 9.5 15 9z"/>
          </svg>
          IA · Smart Insight
        </span>
      </div>
      <p className="ai-insight-text">
        {loading ? "Analisando seus números…" : (insight || defaultInsight)}
      </p>
      <button className="btn-green" onClick={generate} disabled={loading}>
        {loading ? "Pensando…" : (insight ? "Gerar novo insight" : "Ver sugestões")}
      </button>
      <div className="ai-bulb">
        <svg width="80" height="80" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1" opacity="0.18">
          <path d="M9 18h6M10 22h4M12 2a7 7 0 00-4 12.7c1.3 1 2 2.6 2 4.3h4c0-1.7.7-3.3 2-4.3A7 7 0 0012 2z"/>
        </svg>
      </div>
    </div>
  );
}

// ---------- QUICK ACTIONS ----------
function QuickActions({ onAdd }) {
  const actions = [
    { id: "receita", label: "Nova Receita", icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 5v14M5 12h14"/></svg>, color: "bg-green" },
    { id: "despesa", label: "Novo Gasto",   icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14"/></svg>, color: "bg-pink" },
    { id: "divida",  label: "Nova Dívida",  icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 3v18h18"/><path d="M7 14l4-4 4 4 5-7"/></svg>, color: "bg-yellow" },
    { id: "fatura",  label: "Pagar Fatura", icon: <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="2" y="5" width="20" height="14" rx="2"/><path d="M2 10h20"/></svg>, color: "bg-green-soft" },
  ];
  return (
    <div className="card quick-actions">
      <h4>Ações Rápidas</h4>
      <div className="qa-grid">
        {actions.map(a => (
          <button key={a.id} className="qa-btn" onClick={() => onAdd(a.id)}>
            <span className={`qa-icon ${a.color}`}>{a.icon}</span>
            <span className="qa-label">{a.label}</span>
          </button>
        ))}
      </div>
    </div>
  );
}

// ---------- AI RECOMMENDATIONS ----------
function Recommendations({ catData, dividas, monthIncome, monthExpense, onGoTo }) {
  const recs = useMemoP(() => {
    const items = [];
    const topCat = catData[0];
    if (topCat) {
      items.push({
        icon: "🍽️",
        title: `Reduzir ${topCat.category.replace(/[^\w\sÀ-ÿ]/g, "").trim()}`,
        sub: "Definir teto semanal pode economizar até 20%",
        type: "card-light",
      });
    }
    if (dividas.length) {
      const total = dividas.reduce((s, d) => s + d.saldoDevedor, 0);
      items.push({
        icon: "💰",
        title: `Quitar ${window.fmtBRLString(total).replace(",00","")}`,
        sub: `${dividas.length} dívidas pendentes`,
        type: "card-dark",
      });
    }
    const subsCat = catData.find(c => c.category.includes("Assinatura"));
    if (subsCat) {
      items.push({
        icon: "📺",
        title: "Auditar assinaturas",
        sub: `Você gasta ${window.fmtBRLString(subsCat.value).replace(",00","")}/mês`,
        type: "card-light",
      });
    }
    if (monthExpense > monthIncome) {
      items.push({
        icon: "⚠️",
        title: "Mês no vermelho",
        sub: `Déficit de ${window.fmtBRLString(monthExpense - monthIncome).replace(",00","")}`,
        type: "card-alert",
      });
    } else {
      items.push({
        icon: "✨",
        title: "Reserva de Emergência",
        sub: "Meta: 6× despesas mensais",
        type: "card-light",
      });
    }
    return items.slice(0, 3);
  }, [catData, dividas, monthIncome, monthExpense]);

  return (
    <div className="card recommendations clickable" onClick={onGoTo && window.cardNav(() => onGoTo("lancamentos"))} title="Agir no Checklist do mês">
      <div className="card-head">
        <h3>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{verticalAlign:'-2px', marginRight: 6}}>
            <path d="M12 2L9 9l-7 .5 5.5 4.5L6 22l6-4 6 4-1.5-8L22 9.5 15 9z"/>
          </svg>
          Recomendações IA
        </h3>
        <button className="link-btn">Ver todas</button>
      </div>
      <div className="rec-grid">
        {recs.map((r, i) => (
          <div key={i} className={`rec-item ${r.type}`}>
            <div className="rec-icon">{r.icon}</div>
            <div className="rec-title">{r.title}</div>
            <div className="rec-sub">{r.sub}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ---------- RECENT TRANSACTIONS ----------
function RecentTransactions({ txs, onDelete, onViewAll }) {
  const recent = [...txs].sort((a, b) => b.date.localeCompare(a.date)).slice(0, 5);

  function fmtDate(d) {
    const [y, m, dd] = d.split("-");
    return `${dd}/${m}/${y.slice(2)}`;
  }

  return (
    <div className="card recent-tx clickable" onClick={onViewAll && window.cardNav(onViewAll)} title="Ver Checklist do mês">
      <div className="card-head">
        <h3>Lançamentos Recentes</h3>
        <button className="link-btn" onClick={onViewAll}>Ver todos</button>
      </div>
      <div className="tx-list">
        {recent.map(t => {
          const isIncome = t.type === "Receita";
          return (
            <div className="tx-row" key={t.id}>
              <div className={`tx-icon ${isIncome ? "tx-income" : "tx-expense"}`}>
                <span>{(t.category || "•").split(" ")[0]}</span>
              </div>
              <div className="tx-meta">
                <div className="tx-desc">{t.description}</div>
                <div className="tx-date">{fmtDate(t.date)} · {t.account}</div>
              </div>
              <div className={`tx-amount ${isIncome ? "in" : "out"}`}>
                {isIncome ? "+" : "-"}{window.fmtBRLString(t.amount).replace("R$ ", "R$ ").replace("-","")}
              </div>
              <button className="tx-del" onClick={() => onDelete(t.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>
          );
        })}
        {recent.length === 0 && <div className="empty-tx">Nenhum lançamento. Adicione um na barra de ações.</div>}
      </div>
    </div>
  );
}

Object.assign(window, { SpendingOverview, AIInsight, QuickActions, Recommendations, RecentTransactions, Donut, PlanoIndependencia });

// ---------- PLANO 70 / 10 / 10 / 10 (Jim Rohn) ----------
function PlanoIndependencia({ plano, monthLabel, onGoToLancamentos }) {
  const { income, buckets, gastos } = plano;

  function money(v) { return window.fmtBRLString(Math.max(0, v)).replace(",00", ""); }

  return (
    <div className="card plano-card clickable" onClick={onGoToLancamentos && window.cardNav(onGoToLancamentos)} title="Abrir Checklist do mês">
      <div className="plano-head">
        <div className="plano-title">
          <span className="plano-kicker">Independência Financeira · Jim Rohn</span>
          <h3>Plano <b>70</b> · <b>10</b> · <b>10</b> · <b>10</b></h3>
        </div>
        <div className="plano-income">
          <span className="pi-label">Receita base · {monthLabel}</span>
          <Amount value={income}/>
        </div>
      </div>

      {income <= 0 ? (
        <div className="plano-empty">Sem receita lançada neste mês. As metas do plano aparecem assim que houver receita.</div>
      ) : (
        <>
          <div className="plano-grid">
            {buckets.map(b => {
              const fill = Math.min(b.ratio, 1) * 100;
              const isGastos = b.key === "gastos";
              return (
                <div className={`plano-tile ${isGastos ? "pt-gastos" : ""} ${b.over ? "pt-over" : ""}`} key={b.key}>
                  <div className="pt-top">
                    <span className="pt-emoji">{b.icon}</span>
                    <span className="pt-pct">{Math.round(b.pct * 100)}%</span>
                  </div>
                  <div className="pt-label">{b.label}</div>
                  <div className="pt-sub">{isGastos ? "máximo de gastos" : b.sub}</div>
                  <div className="pt-amount">{money(b.used)}</div>
                  <div className="pt-target">de {money(b.target)}</div>
                  <div className="pt-bar"><div className={b.over ? "over" : ""} style={{width: fill + "%"}}/></div>
                  <div className={`pt-status ${b.over ? "neg" : "pos"}`}>
                    {b.over
                      ? `${money(b.used - b.target)} acima`
                      : `falta ${money(b.remaining)}`}
                  </div>
                </div>
              );
            })}
          </div>

          {/* Lever analysis — fitting gastos into 70% */}
          <div className={`plano-lever ${gastos.over ? "lever-over" : "lever-ok"}`}>
            <div className="pl-msg">
              <span className="pl-dot"/>
              {gastos.over ? (
                <span>
                  Gastos <b>{money(gastos.overBy)} acima</b> do teto de 70%. Para caber, corte gastos marcados como <b>redutíveis</b> — você tem <b>{money(gastos.redutivelPendente)}</b> ainda não pagos que podem ser reduzidos.
                </span>
              ) : (
                <span>
                  Gastos dentro do teto de 70%, com folga de <b>{money(gastos.target - gastos.used)}</b>. Mantenha o ritmo.
                </span>
              )}
            </div>
            <div className="pl-stats">
              <div className="pl-stat"><span className="dotmark paid"/>Pago<strong>{money(gastos.gastosPago)}</strong></div>
              <div className="pl-stat"><span className="dotmark pend"/>A pagar<strong>{money(gastos.gastosPendente)}</strong></div>
              <div className="pl-stat"><span className="dotmark redu"/>Redutível<strong>{money(gastos.gastosRedutivel)}</strong></div>
              <button className="pl-link" onClick={onGoToLancamentos}>Revisar lançamentos →</button>
            </div>
          </div>
        </>
      )}
    </div>
  );
}
