// Calculator — the form + the results, including the side-by-side strategy comparison
const { useState: useStateC, useEffect: useEffectC, useMemo: useMemoC } = React;

function Calculator({ openPrivacy, tweaks }) {
  // ---------------- STATE ----------------
  const [filingStatus, setFilingStatus] = useStateC('mfj');
  const [agi, setAgi] = useStateC(135000);
  const [spouseSplit, setSpouseSplit] = useStateC(false);
  const [income1, setIncome1] = useStateC(85000);
  const [income2, setIncome2] = useStateC(50000);
  const [numKids, setNumKids] = useStateC(2);
  const [kidAges, setKidAges] = useStateC([4, 7]);
  const [expenses, setExpenses] = useStateC(18000);
  const [bothWorking, setBothWorking] = useStateC('yes'); // yes / one / no
  const [hasDCFSAPlan, setHasDCFSAPlan] = useStateC('yes'); // yes / no / unsure
  const [stateName, setStateName] = useStateC('CA');

  // Effective AGI
  const effectiveAGI = spouseSplit ? (income1 + income2) : agi;

  // Sync ages array with numKids
  useEffectC(() => {
    setKidAges((cur) => {
      if (cur.length === numKids) return cur;
      if (cur.length < numKids) return [...cur, ...Array(numKids - cur.length).fill(5)];
      return cur.slice(0, numKids);
    });
  }, [numKids]);

  // Eligibility: need both parents earning (or single + working) for both benefits.
  // DCFSA: requires both spouses working, full-time student, or disabled.
  // CDCC: same eligibility rule.
  const eligibleBoth = (filingStatus !== 'mfj' && bothWorking !== 'no') || (filingStatus === 'mfj' && bothWorking === 'yes');
  const hasDCFSA = hasDCFSAPlan === 'yes';
  const kidsUnder13 = kidAges.filter((a) => a < 13).length;
  const kidsUnder17 = kidAges.filter((a) => a < 17).length;

  // Math
  const input = useMemoC(() => ({
    expenses,
    numKids: kidsUnder13,
    agi: effectiveAGI,
    filingStatus,
    hasDCFSA,
    eligibleBoth,
  }), [expenses, kidsUnder13, effectiveAGI, filingStatus, hasDCFSA, eligibleBoth]);

  const strategies = useMemoC(() => FSAMath.buildStrategies(input), [input]);
  const ctc = useMemoC(() => FSAMath.childTaxCredit({
    agi: effectiveAGI,
    numKidsUnder17: kidsUnder17,
    filingStatus,
  }), [effectiveAGI, kidsUnder17, filingStatus]);

  // Hero stats
  const marginal = strategies.recommended.marginalRate;
  const fica = strategies.recommended.ficaRate;
  const cdccR = strategies.recommended.cdccRate;
  const recF = strategies.recommended.F;
  const recCDCCBase = strategies.recommended.cdccEligibleExpenses;

  // ---------------- RENDER ----------------
  return (
    <>
      <div className="card" id="calculator">
        <span className="card-eyebrow">Step 1 — Your situation</span>
        <h2 style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap' }}>
          Tell us about your household
          {tweaks.showInlinePrivacyBadge && (
            <PrivacyBadge onOpenModal={openPrivacy} />
          )}
        </h2>

        <div className="form-section">
          <div>
            <label className="field-label">Filing status</label>
            <Segmented
              value={filingStatus}
              onChange={setFilingStatus}
              options={[
                { value: 'single', label: 'Single' },
                { value: 'hoh', label: 'Head of household' },
                { value: 'mfj', label: 'Married filing jointly' },
                { value: 'mfs', label: 'MFS' },
              ]}
            />
          </div>

          <div className="form-row two">
            <div>
              <label className="field-label" htmlFor="agi">
                {spouseSplit ? 'Spouse 1 earnings' : (filingStatus === 'mfj' ? 'Combined household AGI' : 'Annual AGI')}
              </label>
              <MoneyInput
                id="agi"
                value={spouseSplit ? income1 : agi}
                onChange={spouseSplit ? setIncome1 : setAgi}
                ariaLabel="Adjusted gross income"
                placeholder="e.g. 135000"
              />
              {!spouseSplit && filingStatus === 'mfj' && (
                <div className="field-help">
                  <button
                    type="button"
                    onClick={() => setSpouseSplit(true)}
                    style={{ appearance: 'none', background: 'none', border: 0, color: 'var(--primary)', cursor: 'pointer', textDecoration: 'underline', textUnderlineOffset: 2, padding: 0, font: 'inherit', fontSize: 12 }}
                  >
                    Enter per-spouse incomes →
                  </button>
                </div>
              )}
            </div>
            {spouseSplit ? (
              <div>
                <label className="field-label" htmlFor="agi2">Spouse 2 earnings</label>
                <MoneyInput id="agi2" value={income2} onChange={setIncome2} placeholder="e.g. 50000" ariaLabel="Spouse 2 earnings" />
                <div className="field-help">
                  Combined: <span className="mono">{fmt(effectiveAGI)}</span>{' '}
                  <button
                    type="button"
                    onClick={() => { setSpouseSplit(false); setAgi(income1 + income2); }}
                    style={{ appearance: 'none', background: 'none', border: 0, color: 'var(--primary)', cursor: 'pointer', textDecoration: 'underline', textUnderlineOffset: 2, padding: 0, font: 'inherit', fontSize: 12 }}
                  >
                    use combined →
                  </button>
                </div>
              </div>
            ) : (
              <div>
                <label className="field-label" htmlFor="state">State (informational)</label>
                <select id="state" value={stateName} onChange={(e) => setStateName(e.target.value)}>
                  {['AL','AK','AZ','AR','CA','CO','CT','DE','FL','GA','HI','ID','IL','IN','IA','KS','KY','LA','ME','MD','MA','MI','MN','MS','MO','MT','NE','NV','NH','NJ','NM','NY','NC','ND','OH','OK','OR','PA','RI','SC','SD','TN','TX','UT','VT','VA','WA','WV','WI','WY','DC'].map((s) => (
                    <option key={s} value={s}>{s}</option>
                  ))}
                </select>
                {['CA','NY','OR'].includes(stateName) && (
                  <div className="field-help" style={{ color: 'var(--primary)' }}>
                    {stateName} also has a state-level dependent care benefit — check after you finish here.
                  </div>
                )}
              </div>
            )}
          </div>

          <div className="form-row two">
            <div>
              <label className="field-label">Kids in childcare</label>
              <div style={{ display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap' }}>
                <Stepper value={numKids} onChange={setNumKids} min={0} max={6} />
                <span className="muted" style={{ fontSize: 13 }}>under 13, in paid care</span>
              </div>
              {numKids > 0 && (
                <div className="ages-grid" aria-label="kid ages">
                  {kidAges.map((a, i) => (
                    <span key={i} className="age-chip">
                      Child {i + 1}: age
                      <input
                        type="number"
                        min="0"
                        max="17"
                        value={a}
                        onChange={(e) => {
                          const v = Math.max(0, Math.min(17, parseInt(e.target.value, 10) || 0));
                          setKidAges((cur) => cur.map((x, idx) => (idx === i ? v : x)));
                        }}
                      />
                    </span>
                  ))}
                </div>
              )}
              {numKids > 0 && kidsUnder13 < numKids && (
                <div className="field-help" style={{ color: 'var(--accent)' }}>
                  {numKids - kidsUnder13} of your {numKids} kid{numKids === 1 ? '' : 's'} {numKids - kidsUnder13 === 1 ? 'is' : 'are'} over 13 — not eligible for the dependent-care benefits. Still counted for CTC up to age 17.
                </div>
              )}
            </div>
            <div>
              <label className="field-label" htmlFor="expenses">Annual childcare expenses</label>
              <MoneyInput id="expenses" value={expenses} onChange={setExpenses} placeholder="e.g. 18000" ariaLabel="Annual childcare expenses" />
              <div className="field-help">Daycare, after-school, summer day camp, in-home care. Not overnight camp or tutoring.</div>
            </div>
          </div>

          <div className="form-row two">
            <div>
              <label className="field-label">Both parents working / full-time student / disabled?</label>
              <Segmented
                value={bothWorking}
                onChange={setBothWorking}
                options={[
                  { value: 'yes', label: 'Yes, both' },
                  { value: 'one', label: 'One only' },
                  { value: 'no', label: 'Neither' },
                ]}
              />
              <div className="field-help">
                Both benefits require all working-age caregivers in the household to have earned income (or qualifying student / disability status).
              </div>
            </div>
            <div>
              <label className="field-label">Does your employer offer a Dependent Care FSA?</label>
              <Segmented
                value={hasDCFSAPlan}
                onChange={setHasDCFSAPlan}
                options={[
                  { value: 'yes', label: 'Yes' },
                  { value: 'no', label: 'No' },
                  { value: 'unsure', label: 'Not sure' },
                ]}
              />
              {hasDCFSAPlan === 'unsure' && (
                <div className="field-help">Ask HR for the "Section 129 Dependent Care Assistance Plan" or check your benefits portal at open enrollment.</div>
              )}
            </div>
          </div>
        </div>

        {/* Eligibility warning */}
        {!eligibleBoth && numKids > 0 && expenses > 0 && (
          <div className="eligibility-warn" style={{ marginTop: 20 }}>
            <strong>Heads up:</strong> With only {bothWorking === 'one' ? 'one' : 'no'} working caregiver, neither the DCFSA nor the CDCC is available for most households. The exceptions: the non-working spouse is a full-time student or has a qualifying disability. Read the explainer below for the specifics.
          </div>
        )}
      </div>

      {/* PRE-RESULT AD SLOT — mandatory between input and result */}
      <AdSlot id="pre-result" />

      {/* RESULTS */}
      <div className="card" id="result">
        <span className="card-eyebrow">Step 2 — Your optimal split</span>
        <h2>
          {strategies.recommended.total > 0
            ? <>You can save <span style={{ color: 'var(--primary)' }}>{fmt(strategies.recommended.total)}</span> in federal taxes this year.</>
            : <>Add your income, kids, and childcare expenses above.</>}
        </h2>

        {strategies.recommended.total > 0 && (
          <>
            <div className="stat-row">
              <div className="stat">
                <div className="label">DCFSA contribution</div>
                <div className="val">{fmt(recF)}</div>
                <div className="sub">{recF > 0 ? `elect at open enrollment` : 'skip the FSA this year'}</div>
              </div>
              <div className="stat">
                <div className="label">CDCC expense base</div>
                <div className="val">{fmt(recCDCCBase)}</div>
                <div className="sub">claim on Form 2441 next April</div>
              </div>
              <div className="stat">
                <div className="label">Effective combined rate</div>
                <div className="val">{fmtPct(strategies.recommended.total / Math.max(1, expenses))}</div>
                <div className="sub">of childcare costs offset</div>
              </div>
            </div>

            {/* Strategy comparison row — the hook */}
            {(() => {
              const rec = strategies.recommended;
              const recIsFsaOnly = rec.F === strategies.fsaOnly.F && Math.abs(rec.total - strategies.fsaOnly.total) < 0.5;
              const recIsCreditOnly = rec.F === 0 && Math.abs(rec.total - strategies.creditOnly.total) < 0.5;
              const showSeparateRec = !recIsFsaOnly && !recIsCreditOnly;
              return (
                <>
                  <div className="scroll-hint">← swipe to compare strategies →</div>
                  <div className="strategies-row" role="list" aria-label="strategy comparison">
                    <StrategyCard
                      name="FSA only"
                      sub="Max the DCFSA, skip the credit (you can't claim it on covered expenses anyway)."
                      strategy={strategies.fsaOnly}
                      isRecommended={recIsFsaOnly}
                      recommendedLabel={recIsFsaOnly ? 'Recommended for you' : null}
                      bestTotal={rec.total}
                      showFlag={tweaks.showRecommendedFlag}
                    />
                    <StrategyCard
                      name="Credit only"
                      sub="No DCFSA. Claim the full CDCC expense base."
                      strategy={strategies.creditOnly}
                      isRecommended={recIsCreditOnly}
                      recommendedLabel={recIsCreditOnly ? 'Recommended for you' : null}
                      bestTotal={rec.total}
                      showFlag={tweaks.showRecommendedFlag}
                    />
                    <StrategyCard
                      name="Max both (naive)"
                      sub="What many parents think they get — max FSA + full credit. In reality the IRS subtracts FSA from the credit base."
                      strategy={strategies.maxBothNaive}
                      isNaiveTrap
                      bestTotal={rec.total}
                      showFlag={tweaks.showRecommendedFlag}
                    />
                    {showSeparateRec && (
                      <StrategyCard
                        name="Recommended split"
                        sub="Optimal allocation given your bracket, kid count, and expenses."
                        strategy={rec}
                        isRecommended
                        recommendedLabel="Recommended for you"
                        bestTotal={rec.total}
                        showFlag={tweaks.showRecommendedFlag}
                      />
                    )}
                  </div>
                </>
              );
            })()}

            {/* Allocation visualization */}
            <AllocationCard
              expenses={expenses}
              strategy={strategies.recommended}
              cap={FSAMath.DCFSA_CAP[filingStatus]}
            />

            {/* CTC sidecar */}
            {tweaks.ctcSidecar && (
              <div className="ctc-card">
                <span className="card-eyebrow">Also on your return — Child Tax Credit</span>
                <div className="ctc-row">
                  <span>{kidsUnder17} {kidsUnder17 === 1 ? 'child' : 'children'} under 17</span>
                  <span className="val">×&nbsp;{fmt(2000)}</span>
                </div>
                {ctc.phasedOut > 0 && (
                  <div className="ctc-row">
                    <span className="muted">Phaseout above {fmt(filingStatus === 'mfj' ? 400000 : 200000)}</span>
                    <span className="val" style={{ color: 'var(--accent)' }}>−{fmt(ctc.phasedOut)}</span>
                  </div>
                )}
                <div className="ctc-row total">
                  <span>CTC for {new Date().getFullYear()}</span>
                  <span className="val">{fmt(ctc.credit)}</span>
                </div>
                {ctc.phasedOut > 0 && (
                  <div className="ctc-warning">Your CTC is partially phased out at this income level.</div>
                )}
                <div className="field-help" style={{ marginTop: 4 }}>
                  Separate from the DCFSA/CDCC math — you get this regardless of which dependent-care strategy you pick.
                </div>
              </div>
            )}

            {/* Year-end true-up */}
            <div className="truup-card">
              <h3>What you'll file next April</h3>
              <p>
                {recF > 0 && (
                  <>You'll report your <span className="mono">{fmt(recF)}</span> DCFSA contribution on <strong>Form 2441, Part III</strong>. </>
                )}
                {recCDCCBase > 0 && (
                  <>Claim <span className="mono">{fmt(recCDCCBase)}</span> of dependent care expenses on <strong>Form 2441, Part II</strong> for the Child & Dependent Care Credit ({fmtPct(cdccR)} rate). </>
                )}
                Save your daycare provider's EIN/SSN and an annual receipt — the IRS asks for both.
              </p>
            </div>
          </>
        )}
      </div>
    </>
  );
}

function StrategyCard({ name, sub, strategy, isRecommended, isNaiveTrap, bestTotal, showFlag, recommendedLabel }) {
  const gap = Math.max(0, bestTotal - strategy.total);
  const isLoser = !isRecommended && gap > 0;
  return (
    <div
      className={`strategy-card ${isRecommended ? 'is-recommended' : ''} ${isLoser ? 'is-loser' : ''}`}
      role="listitem"
    >
      {isRecommended && showFlag && <span className="recommended-flag">{recommendedLabel || 'Recommended'}</span>}
      <div className="strategy-name">{name}</div>
      <div className="strategy-sub">{sub}</div>
      <div className="strategy-total">
        <span className="label">Federal savings</span>
        {fmt(strategy.total)}
      </div>
      {gap > 0 && (
        <div className="strategy-gap">
          <span>
            {isNaiveTrap ? 'Same as FSA-only — ' : ''}
            <span className="gap-amount">{fmt(gap)}</span> less than recommended
          </span>
        </div>
      )}
      <div className="strategy-breakdown">
        <div className="line"><span>DCFSA contribution</span><span>{fmt(strategy.F)}</span></div>
        <div className="line"><span>↳ income tax saved</span><span>{fmt(strategy.fsaIncomeTaxSaved)}</span></div>
        <div className="line"><span>↳ FICA saved</span><span>{fmt(strategy.fsaFicaSaved)}</span></div>
        <div className="line"><span>CDCC base</span><span>{fmt(strategy.cdccEligibleExpenses)}</span></div>
        <div className="line"><span>↳ credit @ {fmtPct(strategy.cdccRate)}</span><span>{fmt(strategy.cdccCredit)}</span></div>
      </div>
    </div>
  );
}

function AllocationCard({ expenses, strategy, cap }) {
  const fsa = strategy.F;
  const cdccBase = strategy.cdccEligibleExpenses;
  const out = Math.max(0, expenses - fsa - cdccBase);
  const total = Math.max(1, expenses);
  const fsaPct = (fsa / total) * 100;
  const cdccPct = (cdccBase / total) * 100;
  const outPct = 100 - fsaPct - cdccPct;
  return (
    <div className="alloc-card">
      <div className="alloc-headline">How your {fmt(expenses)} of childcare gets covered</div>
      <p className="alloc-sub">Two federal benefits — sliced by the IRS rule that they don't double-count.</p>
      <div className="alloc-bars">
        <div className="alloc-bar">
          <div className="alloc-bar-head">
            <span className="name">Your annual childcare spend</span>
            <span className="val">{fmt(expenses)}</span>
          </div>
          <div className="alloc-track" role="img" aria-label="allocation breakdown">
            <div className="alloc-seg fsa" style={{ width: `${fsaPct}%` }} title={`DCFSA: ${fmt(fsa)}`} />
            <div className="alloc-seg cdcc" style={{ width: `${cdccPct}%` }} title={`CDCC: ${fmt(cdccBase)}`} />
            <div className="alloc-seg unsaved" style={{ width: `${outPct}%` }} title={`Out of pocket: ${fmt(out)}`} />
          </div>
        </div>
      </div>
      <div className="alloc-legend">
        <span><span className="dot fsa" />DCFSA — {fmt(fsa)} pre-tax</span>
        <span><span className="dot cdcc" />CDCC base — {fmt(cdccBase)} earns credit</span>
        <span><span className="dot unsaved" />Not tax-advantaged — {fmt(out)}</span>
      </div>
    </div>
  );
}

window.Calculator = Calculator;
