// Results panel - hero number, donut, regime bars, breakdown table, tips
const { useState: rUseState, useMemo: rUseMemo, useEffect: rUseEffect } = React;

function ResultsPanel({ result, regime, onPickRegime, onCelebrate, onCompare, onPrint, onShare, onReset, donutThickness = 28 }) {
  const fmt = window.TaxEngine.formatINR;
  const { monthlyTakeHome, annualTakeHome, totalCTC, tdsAnnual, pfEmployerAnnual, pfEmployeeAnnual, gratuityAnnual, profTaxAnnual, variableAnnual, salaryDeductions } = result;

  const donutData = useMemo(() => {
    return [
      { key: "takeHome", label: "Take Home", value: result.fixedTakeHome, color: "var(--accent-green)" },
      { key: "tds", label: "Income Tax", value: tdsAnnual, color: "var(--accent-orange)" },
      { key: "pfEmp", label: "Employee PF", value: pfEmployeeAnnual, color: "var(--accent-blue)" },
      { key: "pfEr", label: "Employer PF", value: pfEmployerAnnual, color: "var(--accent-blue-light)" },
      { key: "grat", label: "Gratuity", value: gratuityAnnual, color: "var(--accent-yellow)" },
      { key: "ptax", label: "Profession Tax", value: profTaxAnnual, color: "var(--accent-gray)" },
      { key: "var", label: "Variable (deferred)", value: variableAnnual, color: "var(--accent-purple)" },
      { key: "sd", label: "Salary deductions", value: salaryDeductions, color: "var(--accent-pink)" },
    ].filter(d => d.value > 0);
  }, [result]);

  // Trigger confetti when monthly take-home crosses 1L threshold
  const prevTakeHome = React.useRef(monthlyTakeHome);
  React.useEffect(() => {
    const prev = prevTakeHome.current;
    if (prev < 100000 && monthlyTakeHome >= 100000) {
      onCelebrate && onCelebrate();
    }
    prevTakeHome.current = monthlyTakeHome;
  }, [monthlyTakeHome, onCelebrate]);

  const breakdown = [
    { label: "Total CTC", monthly: totalCTC / 12, annual: totalCTC, kind: "total" },
    { label: "− Employer PF", monthly: pfEmployerAnnual / 12, annual: pfEmployerAnnual, kind: "deduct", color: "var(--accent-blue-light)" },
    { label: "− Employee PF", monthly: pfEmployeeAnnual / 12, annual: pfEmployeeAnnual, kind: "deduct", color: "var(--accent-blue)" },
    { label: "− Gratuity (deferred)", monthly: gratuityAnnual / 12, annual: gratuityAnnual, kind: "deduct", color: "var(--accent-yellow)" },
    { label: "− Variable (deferred)", monthly: variableAnnual / 12, annual: variableAnnual, kind: "deduct", color: "var(--accent-purple)" },
    { label: "− Profession Tax", monthly: profTaxAnnual / 12, annual: profTaxAnnual, kind: "deduct", color: "var(--accent-gray)" },
    { label: "− Salary deductions", monthly: salaryDeductions / 12, annual: salaryDeductions, kind: "deduct", color: "var(--accent-pink)" },
    { label: "− Income Tax (TDS)", monthly: tdsAnnual / 12, annual: tdsAnnual, kind: "deduct", color: "var(--accent-orange)" },
    { label: "Net Take Home (fixed)", monthly: result.fixedTakeHome / 12, annual: result.fixedTakeHome, kind: "total" },
  ];

  const isEmpty = totalCTC === 0;

  return (
    <aside className="results">
      <div className="results__inner">
        {/* Hero */}
        <div className="results__hero">
          <div className="results__hero-label">Monthly take home</div>
          {isEmpty ? (
            <div style={{ padding: "12px 0 8px", color: "rgba(255,255,255,0.35)", fontSize: 15, lineHeight: 1.5 }}>
              Enter your CTC components above<br />to see your take-home.
            </div>
          ) : (
            <>
              <div className="results__hero-num">
                <AnimatedNumber value={monthlyTakeHome} format={(v) => fmt(v)} />
              </div>
              <div className="results__hero-annual">
                <AnimatedNumber value={annualTakeHome} format={(v) => fmt(v, { compact: true })} /> per year
                {variableAnnual > 0 && <span className="results__hero-note"> (incl. variable)</span>}
              </div>
            </>
          )}

          <div className="results__actions">
            <button className="results__action" onClick={onShare} title="Copy link">
              <svg width="14" height="14" viewBox="0 0 16 16" fill="none"><path d="M8 1v9m0-9L5 4m3-3l3 3M3 11v3a1 1 0 001 1h8a1 1 0 001-1v-3" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
              Share
            </button>
            <button className="results__action" onClick={onCompare} title="Compare scenarios">
              <svg width="14" height="14" viewBox="0 0 16 16" fill="none"><rect x="2" y="3" width="5" height="10" rx="1" stroke="currentColor" strokeWidth="1.5"/><rect x="9" y="3" width="5" height="10" rx="1" stroke="currentColor" strokeWidth="1.5"/></svg>
              Compare
            </button>
            <button className="results__action" onClick={onPrint} title="Print / save PDF">
              <svg width="14" height="14" viewBox="0 0 16 16" fill="none"><path d="M4 5V2h8v3M4 11H2V6h12v5h-2M4 9h8v5H4V9z" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round"/></svg>
              PDF
            </button>
            {!isEmpty && (
              <button className="results__action" onClick={onReset} title="Reset all inputs">
                <svg width="14" height="14" viewBox="0 0 16 16" fill="none"><path d="M2 8a6 6 0 1 0 1.5-4M2 2v4h4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
                Reset
              </button>
            )}
          </div>
        </div>

        {/* Donut */}
        {!isEmpty && <div className="results__card">
          <div className="results__card-title">Where your CTC goes</div>
          <div className="results__donut-wrap">
            <DonutChart
              data={donutData}
              size={240}
              thickness={donutThickness}
              centerLabel="Annual CTC"
              centerValue={fmt(totalCTC, { compact: true })}
            />
            <ul className="results__legend">
              {donutData.map(d => (
                <li key={d.key} className="results__legend-item">
                  <span className="results__legend-swatch" style={{ background: d.color }}></span>
                  <span className="results__legend-label">{d.label}</span>
                  <span className="results__legend-amt">{fmt(d.value, { compact: true })}</span>
                </li>
              ))}
            </ul>
          </div>
        </div>}

        {/* Regime bars */}
        {!isEmpty && <div className="results__card">
          <RegimeBars
            newTax={result.newRegime.totalTax}
            oldTax={result.oldRegime.totalTax}
            betterRegime={result.betterRegime}
            savings={result.regimeSavings}
            regime={regime}
            onPickRegime={onPickRegime}
          />
        </div>}

        {/* Breakdown */}
        {!isEmpty && <div className="results__card">
          <div className="results__card-title">Detailed breakdown</div>
          <table className="results__table">
            <thead>
              <tr><th></th><th>Monthly</th><th>Annual</th></tr>
            </thead>
            <tbody>
              {breakdown.map((row, i) => (
                <tr key={i} className={`results__table-row results__table-row--${row.kind}`}>
                  <td className="results__table-label">
                    {row.color && <span className="results__table-dot" style={{ background: row.color }}></span>}
                    {row.label}
                  </td>
                  <td className="results__table-num">{fmt(row.monthly)}</td>
                  <td className="results__table-num">{fmt(row.annual, { compact: true })}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>}

        {/* Tips */}
        {!isEmpty && <TaxTips result={result} />}
      </div>
    </aside>
  );
}

// Tax savings tips - dynamic based on result
function TaxTips({ result }) {
  const fmt = window.TaxEngine.formatINR;
  const tips = [];

  // 80C unused (old regime)
  const sec80CUsed = result.oldRegime.sec80C;
  if (sec80CUsed < 150000) {
    const room = 150000 - sec80CUsed;
    tips.push({
      key: "80c",
      title: `Max your 80C — ₹${(room / 1000).toFixed(0)}K of room left`,
      body: "ELSS funds, life insurance premiums, PPF, and 5-yr FDs all qualify. Saves up to 30% in old regime.",
      impact: room * 0.3,
    });
  }

  // NPS 80CCD(1B) (old regime extra ₹50K)
  if (result.oldRegime.sec80CCD1B < 50000) {
    tips.push({
      key: "nps1b",
      title: "NPS Tier-I — extra ₹50K deduction (80CCD(1B))",
      body: "Over-and-above 80C limit. A no-brainer if you want to lock in retirement savings.",
      impact: (50000 - result.oldRegime.sec80CCD1B) * 0.3,
    });
  }

  // Employer NPS (works in both)
  const basicAnnual = result.basicAnnual;
  const empNPSCap = basicAnnual * 0.14;
  if (result.oldRegime.sec80CCD2 < empNPSCap && empNPSCap > 1000) {
    tips.push({
      key: "nps2",
      title: "Ask HR about Employer NPS contribution (80CCD(2))",
      body: `Up to 14% of Basic — works in BOTH regimes. Cap for you: ${fmt(empNPSCap, { compact: true })}/yr.`,
      impact: (empNPSCap - result.oldRegime.sec80CCD2) * 0.3,
    });
  }

  // Regime mismatch
  if (result.regime !== result.betterRegime && result.regimeSavings > 1000) {
    tips.push({
      key: "regime",
      title: `Switch to ${result.betterRegime === "new" ? "New" : "Old"} Regime`,
      body: `You'd save ${fmt(result.regimeSavings)} per year based on your current inputs.`,
      impact: result.regimeSavings,
      priority: true,
    });
  }

  // HRA underclaim
  if (result.regime === "old" && (result.annual.hra || 0) > 0 && result.oldRegime.hraExemption === 0) {
    tips.push({
      key: "hra",
      title: "You're getting HRA but not claiming exemption",
      body: "Add your monthly rent in the Exemptions section to claim HRA exemption.",
      impact: 0,
    });
  }

  if (tips.length === 0) {
    return (
      <div className="tips tips--empty">
        <div className="tips__title">Looking good 👌</div>
        <div className="tips__body">You've maxed your major deductions. Verify with a CA before filing.</div>
      </div>
    );
  }

  // Sort by priority then impact
  tips.sort((a, b) => (b.priority ? 1 : 0) - (a.priority ? 1 : 0) || b.impact - a.impact);

  return (
    <div className="tips">
      <div className="tips__head">
        <div className="tips__title">💡 Tax-saving ideas</div>
        <div className="tips__sub">Based on your inputs — verify with a CA</div>
      </div>
      <ul className="tips__list">
        {tips.slice(0, 4).map(t => (
          <li key={t.key} className={`tips__item ${t.priority ? "is-priority" : ""}`}>
            <div className="tips__item-title">{t.title}</div>
            <div className="tips__item-body">{t.body}</div>
            {t.impact > 0 && (
              <div className="tips__item-impact">Potential save: ~{fmt(t.impact, { compact: true })}/yr</div>
            )}
          </li>
        ))}
      </ul>
    </div>
  );
}

Object.assign(window, { ResultsPanel, TaxTips });
