// Right-column results panel.

const fmt0 = (n) => {
  if (n == null || !isFinite(n)) return '—';
  const v = Math.round(n);
  return (v < 0 ? '−' : '') + '$' + Math.abs(v).toLocaleString('en-US');
};
const fmt0Plain = (n) => '$' + Math.round(n).toLocaleString('en-US');

function tierFor(netBenefit, taxOnlySavings) {
  if (netBenefit > 3000) return 'good';
  if (netBenefit > 0) return 'warn';
  if (taxOnlySavings > 0 && netBenefit > -2000) return 'warn';
  return 'bad';
}

function verdictCopy(tier, netBenefit, state, overheadTotal) {
  if (tier === 'good') return {
    pill: 'Likely worth it',
    headline: fmt0(netBenefit),
    sub: `Estimated annual net benefit after the ~${fmt0Plain(overheadTotal)} of added overhead. The gap is comfortable — the S-Corp election makes sense at this income level.`
  };
  if (tier === 'warn' && netBenefit > 0) return {
    pill: 'Marginal',
    headline: fmt0(netBenefit),
    sub: `You'd come out ahead, but only barely. One unexpected accounting bill or missed payroll deadline could erase the gain. Strongly consider waiting until your numbers grow more.`
  };
  if (tier === 'warn') return {
    pill: 'Borderline',
    headline: fmt0(netBenefit),
    sub: `Tax savings exist, but overhead eats them. A small income bump pushes you into worth-it territory — keep an eye on the threshold below.`
  };
  return {
    pill: 'Not worth it',
    headline: fmt0(netBenefit),
    sub: `At this income level the overhead and complexity outweigh the SE-tax savings. Stay as you are; revisit when net income clears the break-even line below.`
  };
}

function VerdictCard({ result, breakEven, s }) {
  const tier = tierFor(result.netBenefit, result.taxOnlySavings);
  const copy = verdictCopy(tier, result.netBenefit, result.state, result.overheadTotal);
  const isNeg = result.netBenefit < 0;

  // Position the user marker on the gradient track relative to break-even
  // Range: 0.5× break-even on the left, 2× break-even on the right.
  let leftPct = 50;
  let breakEvenPct = 50;
  if (breakEven) {
    const lo = breakEven * 0.4;
    const hi = breakEven * 2.0;
    const clamp = (x) => Math.max(0, Math.min(100, x));
    leftPct = clamp(((s.netIncome - lo) / (hi - lo)) * 100);
    breakEvenPct = clamp(((breakEven - lo) / (hi - lo)) * 100);
  }

  const distToBreakEven = breakEven ? s.netIncome - breakEven : null;

  return (
    <div className="result-card verdict-card" data-tier={tier}>
      <div className="verdict-pill">
        <span className="dot"></span>
        <span>{copy.pill}</span>
      </div>
      <div className={"verdict-headline" + (isNeg ? ' minus' : '')}>
        {copy.headline}
        <span style={{
          fontSize: 14, fontFamily: 'var(--mono)', fontStyle: 'normal',
          color: 'var(--ink-3)', marginLeft: 10, verticalAlign: 'middle',
        }}>/ year</span>
      </div>
      <div className="verdict-sub">{copy.sub}</div>

      <div className="breakeven-block">
        <span className="breakeven-label">Break-even threshold · {result.state.name}</span>
        <span className="breakeven-value">
          {breakEven ? fmt0Plain(breakEven) : 'Not reached'}
          <span style={{
            fontSize: 12, fontFamily: 'var(--mono)', fontStyle: 'normal',
            color: 'var(--ink-3)', marginLeft: 10,
          }}>
            net business income / year
          </span>
        </span>
      </div>

      {breakEven && (
        <div className="viz">
          <div className="viz-track">
            <div className="viz-breakeven" style={{ left: breakEvenPct + '%' }}></div>
            <div className="viz-marker" style={{ left: leftPct + '%' }}></div>
          </div>
          <div className="viz-labels">
            <span>{fmt0Plain(breakEven * 0.4)}</span>
            <span style={{ color: 'var(--ink-2)' }}>break-even {fmt0Plain(breakEven)}</span>
            <span>{fmt0Plain(breakEven * 2.0)}</span>
          </div>
          <div className="viz-callout">
            You're at <strong>{fmt0Plain(s.netIncome)}</strong> — that's{' '}
            <strong>{fmt0Plain(Math.abs(distToBreakEven))}</strong>{' '}
            {distToBreakEven >= 0 ? 'above' : 'below'} the break-even point for{' '}
            {result.state.name}.
          </div>
        </div>
      )}
    </div>
  );
}

function CompareCard({ result, s }) {
  const sp = result.sp;
  const sc = result.sc;
  const row = (label, a, b, opt = {}) => {
    const delta = a - b;
    return (
      <tr key={label}>
        <td>{label}</td>
        <td>{opt.dash && a === 0 ? '—' : fmt0Plain(a)}</td>
        <td>{opt.dash && b === 0 ? '—' : fmt0Plain(b)}</td>
        <td className={"delta-cell" + (delta < 0 ? ' neg' : '')}>
          {delta === 0 ? '—' : (delta > 0 ? '−' : '+') + fmt0Plain(Math.abs(delta))}
        </td>
      </tr>
    );
  };

  return (
    <div className="result-card compare-card">
      <div className="compare-head">
        <div className="compare-title">Line-by-line comparison</div>
        <div className="compare-sub">
          At ${s.netIncome.toLocaleString()} net income, S-Corp salary {fmt0Plain(s.salary)}
        </div>
      </div>
      <table className="compare-table">
        <thead>
          <tr>
            <th>Item</th>
            <th>{s.entity === 'sole' ? 'Sole prop' : 'LLC'}</th>
            <th>S-Corp</th>
            <th>You save</th>
          </tr>
        </thead>
        <tbody>
          <tr className="subhead"><td colSpan="4">Payroll / SE taxes</td></tr>
          {row('Self-employment tax', sp.seTax, 0, { dash: true })}
          {row('Payroll tax (SS + Medicare)', 0, sc.payrollTax, { dash: true })}

          <tr className="subhead"><td colSpan="4">Income taxes</td></tr>
          {row('Federal income tax', sp.fedTax, sc.fedTax)}
          {row('State income tax', sp.stateTax, sc.stateTax)}
          {row('State S-Corp / entity tax', 0, sc.entityTax, { dash: true })}
          {row('QBI deduction (reduces fed)', -sp.qbiDeduction * 0.22, -sc.qbiDeduction * 0.22)}

          <tr className="subhead"><td colSpan="4">Overhead</td></tr>
          {row('Compliance & filing costs', 0, sc.overhead, { dash: true })}

          <tr className="total">
            <td>Total annual cost</td>
            <td>{fmt0Plain(sp.total)}</td>
            <td>{fmt0Plain(sc.total)}</td>
            <td className={"delta-cell" + (result.netBenefit < 0 ? ' neg' : '')}>
              {result.netBenefit >= 0 ? '+' : '−'}{fmt0Plain(Math.abs(result.netBenefit))}
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  );
}

function StateNoteCard({ result, s }) {
  const notes = [...result.state.notes];

  // Add a few derived notes based on input
  const overheadParts = [];
  if (s.payroll) overheadParts.push(`payroll ${fmt0Plain(s.payroll)}`);
  if (s.taxPrep) overheadParts.push(`tax prep ${fmt0Plain(s.taxPrep)}`);
  if (result.state.llcAnnualFee) overheadParts.push(`${result.state.name} fee ${fmt0Plain(result.state.llcAnnualFee)}`);

  // Election deadline note
  const today = new Date();
  const year = today.getFullYear();
  const mar15 = new Date(year, 2, 15);
  const daysToMar15 = Math.round((mar15 - today) / (1000 * 60 * 60 * 24));
  const deadlineNote = daysToMar15 > 0
    ? `Form 2553 due ${mar15.toLocaleDateString('en-US', { month: 'long', day: 'numeric' })} for ${year} tax year — that's ${daysToMar15} days from now.`
    : `Form 2553 deadline for ${year} (March 15) has passed. Election now applies to ${year + 1} — or use late-election relief (Rev. Proc. 2013-30) within 3 years 75 days.`;

  return (
    <div className="result-card note-card">
      <h4>{result.state.name} · what to know</h4>
      <ul>
        {notes.length === 0 ? (
          <li>No state-specific S-Corp adders — election impact is mostly federal here.</li>
        ) : notes.map((n, i) => <li key={i}>{n}</li>)}
        <li>{deadlineNote}</li>
        <li>
          New entities have <strong>75 days</strong> from formation to file Form 2553
          to take effect immediately.
        </li>
      </ul>
    </div>
  );
}

function ResultsPanel({ result, breakEven, s, showAds }) {
  return (
    <div className="results">
      {showAds && (
        <AdSlot
          size="mrec"
          slotId="pre-result"
          className="ad-pre-result"
          label="Pre-result — between form and answer"
        />
      )}
      <VerdictCard result={result} breakEven={breakEven} s={s} />
      <CompareCard result={result} s={s} />
      <StateNoteCard result={result} s={s} />
    </div>
  );
}

window.ResultsPanel = ResultsPanel;
