// Hike Calculator — preview feature
const { useState: hUseState, useMemo: hUseMemo } = React;

function HikeCalculator({ state }) {
  const fmt = window.TaxEngine.formatINR;
  const [hikePct, setHikePct] = hUseState(10);

  const isEmpty = !state.monthly.basic && !state.monthly.special;

  // Apply hike % to all monthly components and variable
  const hikedState = hUseMemo(() => {
    const m = 1 + hikePct / 100;
    const newMonthly = {};
    for (const k in state.monthly) {
      newMonthly[k] = Math.round((state.monthly[k] || 0) * m);
    }
    return { ...state, monthly: newMonthly, variable: Math.round((state.variable || 0) * m) };
  }, [state, hikePct]);

  const before = hUseMemo(() => window.TaxEngine.computeTakeHome(state), [state]);
  const after  = hUseMemo(() => window.TaxEngine.computeTakeHome(hikedState), [hikedState]);

  const monthlyDelta = after.monthlyTakeHome - before.monthlyTakeHome;
  const annualDelta  = after.annualTakeHome  - before.annualTakeHome;
  const ctcDelta     = after.totalCTC        - before.totalCTC;
  const effectivePct = before.monthlyTakeHome > 0
    ? ((monthlyDelta / before.monthlyTakeHome) * 100)
    : 0;
  const taxDrag = ctcDelta > 0
    ? (((ctcDelta - monthlyDelta * 12) / ctcDelta) * 100)
    : 0;

  return (
    <div className="hike">
      {/* Header */}
      <div className="hike__head">
        <div className="hike__eyebrow">Beta · Appraisal season 2026</div>
        <h2 className="hike__title">How much more lands in your account?</h2>
        <p className="hike__desc">
          Enter your hike percentage below. We'll calculate the exact take-home increase after tax, PF, and regime — using your current salary inputs.
        </p>
      </div>

      {isEmpty && (
        <div className="hike__empty">
          <div className="hike__empty-icon">💡</div>
          <div className="hike__empty-text">Fill in your current salary in the <strong>Salary Calculator</strong> tab first, then come back here.</div>
        </div>
      )}

      {!isEmpty && (
        <>
          {/* Hike % slider */}
          <div className="hike__slider-wrap">
            <div className="hike__slider-label">
              <span className="hike__slider-title">Your hike</span>
              <div className="hike__slider-val-wrap">
                <input
                  type="number"
                  className="hike__slider-input"
                  min={1} max={60}
                  value={hikePct}
                  onChange={e => {
                    const v = Math.min(60, Math.max(1, Number(e.target.value) || 1));
                    setHikePct(v);
                  }}
                />
                <span className="hike__slider-val">%</span>
              </div>
            </div>
            <input
              type="range"
              className="hike__slider"
              min={1} max={60} step={1}
              value={hikePct}
              onChange={e => setHikePct(Number(e.target.value))}
            />
            <div className="hike__slider-ticks">
              {[5, 10, 15, 20, 25, 30, 40, 50, 60].map(v => (
                <button key={v} className={`hike__tick ${hikePct === v ? "is-active" : ""}`} onClick={() => setHikePct(v)}>{v}%</button>
              ))}
            </div>
          </div>

          {/* Before / After */}
          <div className="hike__compare">
            <div className="hike__col hike__col--before">
              <div className="hike__col-label">Current</div>
              <div className="hike__col-ctc">{fmt(before.totalCTC, { compact: true })} CTC</div>
              <div className="hike__col-takehome">{fmt(before.monthlyTakeHome)}</div>
              <div className="hike__col-per">/month in hand</div>
              <div className="hike__col-annual">{fmt(before.annualTakeHome, { compact: true })}/yr</div>
            </div>

            <div className="hike__arrow">
              <div className="hike__arrow-pct">+{hikePct}%</div>
              <svg width="32" height="32" viewBox="0 0 32 32" fill="none">
                <path d="M6 16h20M20 10l6 6-6 6" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            </div>

            <div className="hike__col hike__col--after">
              <div className="hike__col-label">After hike</div>
              <div className="hike__col-ctc">{fmt(after.totalCTC, { compact: true })} CTC</div>
              <div className="hike__col-takehome" style={{ color: "var(--accent-green)" }}>{fmt(after.monthlyTakeHome)}</div>
              <div className="hike__col-per">/month in hand</div>
              <div className="hike__col-annual">{fmt(after.annualTakeHome, { compact: true })}/yr</div>
            </div>
          </div>

          {/* Delta cards */}
          <div className="hike__deltas">
            <div className="hike__delta-card hike__delta-card--main">
              <div className="hike__delta-label">Extra per month</div>
              <div className="hike__delta-val">{fmt(monthlyDelta, { sign: true })}</div>
              <div className="hike__delta-sub">in-hand after all deductions</div>
            </div>
            <div className="hike__delta-card">
              <div className="hike__delta-label">Extra per year</div>
              <div className="hike__delta-val">{fmt(annualDelta, { compact: true, sign: true })}</div>
              <div className="hike__delta-sub">annual take-home increase</div>
            </div>
            <div className="hike__delta-card">
              <div className="hike__delta-label">Effective hike</div>
              <div className="hike__delta-val">{effectivePct > 0 ? "+" : ""}{effectivePct.toFixed(1)}%</div>
              <div className="hike__delta-sub">on your take-home vs {hikePct}% gross</div>
            </div>
            <div className="hike__delta-card">
              <div className="hike__delta-label">Tax drag on hike</div>
              <div className="hike__delta-val">{taxDrag.toFixed(1)}%</div>
              <div className="hike__delta-sub">of your hike goes to tax & PF</div>
            </div>
          </div>

          {/* Insight */}
          <div className="hike__insight">
            💡 Your {hikePct}% gross hike translates to a <strong>{effectivePct.toFixed(1)}% effective take-home increase</strong> — {fmt(monthlyDelta)} more every month. Tax and PF absorb {taxDrag.toFixed(0)}% of the raise.
          </div>

          {/* Full CTC breakdown */}
          <HikeBreakdown before={before} after={after} state={state} hikedState={hikedState} hikePct={hikePct} />
        </>
      )}
    </div>
  );
}

function HikeBreakdown({ before, after, state, hikedState, hikePct }) {
  const fmt = window.TaxEngine.formatINR;

  const LABELS = {
    basic: "Basic Salary",
    hra: "HRA",
    conveyance: "Conveyance",
    medical: "Medical",
    telephone: "Telephone",
    lta: "LTA",
    meal: "Meal Vouchers",
    cea: "Children Education",
    car: "Car Allowance",
    special: "Special Allowance",
    statutory: "Statutory Bonus",
    other: "Other Allowance",
    gratuity: "Gratuity",
  };

  // CTC components (monthly)
  const ctcRows = Object.entries(LABELS)
    .map(([key, label]) => ({
      label,
      before: state.monthly[key] || 0,
      after: hikedState.monthly[key] || 0,
    }))
    .filter(r => r.before > 0 || r.after > 0);

  // Add employer PF
  ctcRows.push({
    label: "Employer PF",
    before: before.pfEmployerAnnual / 12,
    after: after.pfEmployerAnnual / 12,
  });

  // Variable (annual, shown separately)
  const hasVariable = (state.variable || 0) > 0;
  const hasBonus    = (state.bonusAnnual || 0) > 0;

  // Deduction rows (monthly)
  const dedRows = [
    { label: "Employee PF", before: before.pfEmployeeAnnual / 12, after: after.pfEmployeeAnnual / 12 },
    { label: "Gratuity (accrual)", before: before.gratuityAnnual / 12, after: after.gratuityAnnual / 12 },
    { label: "Profession Tax", before: before.profTaxAnnual / 12, after: after.profTaxAnnual / 12 },
    { label: "Income Tax (TDS)", before: before.fixedTdsAnnual / 12, after: after.fixedTdsAnnual / 12 },
  ].filter(r => r.before > 0 || r.after > 0);

  const Delta = ({ b, a, annual = false }) => {
    const d = a - b;
    if (Math.abs(d) < 1) return <span className="hike__bd-delta hike__bd-delta--nil">—</span>;
    const opts = annual ? { compact: true, sign: true } : { sign: true };
    return (
      <span className={`hike__bd-delta ${d > 0 ? "hike__bd-delta--pos" : "hike__bd-delta--neg"}`}>
        {fmt(d, opts)}
      </span>
    );
  };

  const Row = ({ label, b, a, annual = false, bold = false }) => (
    <tr className={`hike__bd-row ${bold ? "hike__bd-row--total" : ""}`}>
      <td className="hike__bd-name">{label}{annual && <span className="hike__bd-yr">/yr</span>}</td>
      <td className="hike__bd-num">{fmt(b, annual ? { compact: true } : {})}</td>
      <td className="hike__bd-num hike__bd-num--after">{fmt(a, annual ? { compact: true } : {})}</td>
      <td className="hike__bd-num"><Delta b={b} a={a} annual={annual} /></td>
    </tr>
  );

  const SectionHead = ({ title }) => (
    <tr className="hike__bd-section">
      <td colSpan={4}>{title}</td>
    </tr>
  );

  return (
    <div className="hike__breakdown">
      <div className="hike__bd-title">Full salary breakdown — before vs after</div>
      <table className="hike__bd-table">
        <thead>
          <tr>
            <th></th>
            <th>Current <span className="hike__bd-th-sub">/mo</span></th>
            <th>After +{hikePct}% <span className="hike__bd-th-sub">/mo</span></th>
            <th>Change</th>
          </tr>
        </thead>
        <tbody>
          <SectionHead title="CTC Components" />
          {ctcRows.map(r => <Row key={r.label} label={r.label} b={r.before} a={r.after} />)}
          {hasVariable && <Row label="Variable Pay" b={state.variable} a={hikedState.variable} annual />}
          {hasBonus    && <Row label="Annual Bonus" b={state.bonusAnnual} a={hikedState.bonusAnnual} annual />}
          <Row label="Total CTC" b={before.totalCTC / 12} a={after.totalCTC / 12} bold />

          <SectionHead title="Deductions from salary" />
          {dedRows.map(r => <Row key={r.label} label={r.label} b={r.before} a={r.after} />)}
          <Row label="Total deductions" b={dedRows.reduce((s, r) => s + r.before, 0)} a={dedRows.reduce((s, r) => s + r.after, 0)} bold />

          <SectionHead title="Take-home" />
          <Row label="Monthly take-home" b={before.monthlyTakeHome} a={after.monthlyTakeHome} bold />
          <Row label="Annual take-home" b={before.annualTakeHome} a={after.annualTakeHome} annual bold />
        </tbody>
      </table>
    </div>
  );
}

Object.assign(window, { HikeCalculator });
