// Input sections — accordion bodies
const { useState: sUseState } = React;

const SECTION_ICONS = {
  ctc: "💰",
  other: "📋",
  exemptions: "🏠",
  deductions: "📉",
  income: "💼",
};

function CTCSection({ state, setState }) {
  const fmt = window.TaxEngine.formatINR;
  const updateMonthly = (key, value) => {
    setState(s => ({ ...s, monthly: { ...s.monthly, [key]: value } }));
  };

  const basicMonthly = state.monthly.basic || 0;
  const pfEmployerMonthly = basicMonthly * 0.12;

  // Default visible component keys
  const DEFAULT_KEYS = ["basic", "hra", "lta", "cea", "special"];
  const ADDABLE_KEYS = ["conveyance", "medical", "telephone", "meal", "car", "other", "gratuity"];

  const [extraKeys, setExtraKeys] = sUseState(() => {
    // auto-show any addable that already has a value (from URL state)
    return ADDABLE_KEYS.filter(k => (state.monthly[k] || 0) > 0);
  });
  const [showVariable, setShowVariable] = sUseState((state.variable || 0) > 0);
  const [showBonus, setShowBonus] = sUseState((state.bonusAnnual || 0) > 0);
  const [showRSU, setShowRSU] = sUseState((state.rsuAnnual || 0) > 0);

  const visibleKeys = [...DEFAULT_KEYS, ...extraKeys];
  const remainingKeys = ADDABLE_KEYS.filter(k => !extraKeys.includes(k));

  const removeKey = (key) => {
    updateMonthly(key, 0);
    setExtraKeys(ks => ks.filter(k => k !== key));
  };

  return (
    <AccordionSection
      id="ctc"
      title="CTC Components"
      subtitle="Monthly inputs · annual auto-calculated"
      icon={SECTION_ICONS.ctc}
      defaultOpen={false}
    >
      <div className="grid">
        {visibleKeys.map(key => {
          const cfg = window.SLIDER_CONFIGS[key];
          if (!cfg) return null;
          const [min, max, step, label, hint] = cfg;
          const isExtra = extraKeys.includes(key);
          return (
            <div key={key} className="slider-input-wrap">
              {isExtra && (
                <button className="slider-input__remove" onClick={() => removeKey(key)} title="Remove">×</button>
              )}
              <SliderInput
                label={label}
                value={state.monthly[key] || 0}
                onChange={(v) => updateMonthly(key, v)}
                min={min}
                max={max}
                step={step}
                hint={hint}
              />
            </div>
          );
        })}

        {/* PF Employer - auto */}
        <SliderInput
          label="PF Employer (12% of Basic)"
          value={pfEmployerMonthly}
          onChange={() => {}}
          min={0}
          max={Math.max(60000, pfEmployerMonthly * 1.5)}
          step={1}
          readOnly={true}
          hint="Auto: 12% of Basic. Employer contribution to your EPF account."
        />

        {showVariable && (
          <div className="slider-input-wrap">
            <button className="slider-input__remove" onClick={() => { setState(s => ({ ...s, variable: 0 })); setShowVariable(false); }}>×</button>
            <SliderInput
              label="Variable pay"
              value={state.variable || 0}
              onChange={(v) => setState(s => ({ ...s, variable: v }))}
              min={0} max={5000000} step={5000} suffix="/yr" annualMultiplier={1}
              hint="Annual figure. Paid as bonus — deferred from monthly take-home."
            />
          </div>
        )}
        {showBonus && (
          <div className="slider-input-wrap">
            <button className="slider-input__remove" onClick={() => { setState(s => ({ ...s, bonusAnnual: 0 })); setShowBonus(false); }}>×</button>
            <SliderInput
              label="Annual Bonus"
              value={state.bonusAnnual || 0}
              onChange={(v) => setState(s => ({ ...s, bonusAnnual: v }))}
              min={0} max={5000000} step={5000} suffix="/yr" annualMultiplier={1}
              hint="Joining bonus, performance, retention. Taxed as salary income."
            />
          </div>
        )}
        {showRSU && (
          <div className="slider-input-wrap">
            <button className="slider-input__remove" onClick={() => { setState(s => ({ ...s, rsuAnnual: 0 })); setShowRSU(false); }}>×</button>
            <SliderInput
              label="RSU / ESOPs (annual vest)"
              value={state.rsuAnnual || 0}
              onChange={(v) => setState(s => ({ ...s, rsuAnnual: v }))}
              min={0} max={20000000} step={10000} suffix="/yr" annualMultiplier={1}
              hint="Value of stock vesting this year. Taxed as perquisite at slab rate."
            />
          </div>
        )}
      </div>

      {/* Add more chips */}
      <div className="add-chips">
        <span className="add-chips__label">+ Add</span>
        {remainingKeys.map(key => {
          const [, , , label] = window.SLIDER_CONFIGS[key];
          return (
            <button key={key} className="add-chip" onClick={() => setExtraKeys(ks => [...ks, key])}>
              + {label}
            </button>
          );
        })}
        {!showVariable && <button className="add-chip" onClick={() => setShowVariable(true)}>+ Variable pay</button>}
        {!showBonus && <button className="add-chip" onClick={() => setShowBonus(true)}>+ Annual Bonus</button>}
        {!showRSU && <button className="add-chip" onClick={() => setShowRSU(true)}>+ RSU / ESOPs</button>}
      </div>
    </AccordionSection>
  );
}

function OtherDetailsSection({ state, setState, regimeSavings, betterRegime }) {
  return (
    <AccordionSection
      id="other"
      title="Other Details"
      subtitle="Regime · profession tax · salary deductions"
      icon={SECTION_ICONS.other}
    >
      <div className="form-stack">
        <div className="form-stack__row">
          <div className="form-stack__label">
            <div>Tax regime</div>
            <div className="form-stack__hint">New regime is the default since FY 2023-24</div>
          </div>
          <RegimeSwitch
            regime={state.regime}
            onChange={(r) => setState(s => ({ ...s, regime: r }))}
            betterRegime={betterRegime}
            savings={regimeSavings}
          />
        </div>

        <SliderInput
          label="Profession Tax"
          value={state.profTaxMonthly}
          onChange={(v) => setState(s => ({ ...s, profTaxMonthly: v }))}
          min={0}
          max={2500 / 12}
          step={1}
          hint="State-level tax. ₹200/mo standard for most metros. Deductible under both regimes."
        />

        <SliderInput
          label="Other salary deductions"
          value={state.salaryDeductions / 12}
          onChange={(v) => setState(s => ({ ...s, salaryDeductions: v * 12 }))}
          min={0}
          max={50000}
          step={100}
          hint="E.g. food/transport recovery, insurance premiums recovered from salary."
        />
      </div>
    </AccordionSection>
  );
}

function ExemptionsSection({ state, setState, hraExemption }) {
  const fmt = window.TaxEngine.formatINR;
  const dim = state.regime === "new";
  const updateEx = (key, value) => {
    setState(s => ({ ...s, exemptions: { ...s.exemptions, [key]: value } }));
  };

  return (
    <AccordionSection
      id="exemptions"
      title="Exemptions (Old Regime)"
      subtitle={dim ? "Disabled — switch to Old Regime to claim" : "HRA, LTA, telephone, meal, car, CEA"}
      icon={SECTION_ICONS.exemptions}
      dim={dim}
    >
      <div className="form-stack">
        <div className="form-stack__row">
          <div className="form-stack__label">
            <div>Metro city?</div>
            <div className="form-stack__hint">From FY 2026-27, metros include Mumbai, Delhi, Kolkata, Chennai, Bengaluru, Pune, Hyderabad, Ahmedabad. 50% of Basic vs 40%.</div>
          </div>
          <Toggle
            checked={state.isMetro}
            onChange={(v) => setState(s => ({ ...s, isMetro: v }))}
            labelOn="Metro (50%)"
            labelOff="Non-metro (40%)"
            disabled={dim}
          />
        </div>

        <SliderInput
          label="Rent paid"
          value={state.exemptions.rentMonthly}
          onChange={(v) => updateEx("rentMonthly", v)}
          min={0}
          max={200000}
          step={500}
          disabled={dim}
          hint={!dim && hraExemption > 0 ? `HRA exemption: ${fmt(hraExemption, { compact: true })}/yr` : "Min of: City% of Basic, Rent − 10% Basic, HRA received"}
        />

        <SliderInput
          label="LTA claim"
          value={state.exemptions.ltaClaim / 12}
          onChange={(v) => updateEx("ltaClaim", v * 12)}
          min={0}
          max={100000}
          step={500}
          disabled={dim}
          hint="Twice in 4-yr block, against actual travel. Capped at LTA received."
        />
        <SliderInput
          label="Telephone reimbursement"
          value={state.exemptions.telephoneClaim / 12}
          onChange={(v) => updateEx("telephoneClaim", v * 12)}
          min={0}
          max={30000}
          step={100}
          disabled={dim}
          hint="Against actual bills. Capped at telephone allowance received."
        />
        <SliderInput
          label="Meal voucher claim"
          value={state.exemptions.mealClaim / 12}
          onChange={(v) => updateEx("mealClaim", v * 12)}
          min={0}
          max={30000}
          step={100}
          disabled={dim}
          hint="₹50/meal × 22 working days × 12 months ≈ ₹13.2K/yr exempt."
        />
        <SliderInput
          label="Car allowance claim"
          value={state.exemptions.carClaim / 12}
          onChange={(v) => updateEx("carClaim", v * 12)}
          min={0}
          max={100000}
          step={500}
          disabled={dim}
          hint="Against fuel/maintenance bills."
        />
        <SliderInput
          label="Children Education claim"
          value={state.exemptions.ceaClaim / 12}
          onChange={(v) => updateEx("ceaClaim", v * 12)}
          min={0}
          max={20000}
          step={50}
          disabled={dim}
          hint="₹100/child/month for up to 2 children = ₹2,400/yr."
        />
      </div>
    </AccordionSection>
  );
}

function DeductionsSection({ state, setState, basicAnnual, pfEmployeeAnnual }) {
  const fmt = window.TaxEngine.formatINR;
  const dim = state.regime === "new";
  const updateDed = (key, value) => {
    setState(s => ({ ...s, deductions: { ...s.deductions, [key]: value } }));
  };

  const sec80CUsed = (state.deductions.c80 || 0) + pfEmployeeAnnual;
  const empNPSCap = basicAnnual * 0.14;

  return (
    <AccordionSection
      id="deductions"
      title="Deductions"
      subtitle={dim ? "Most disabled in New Regime — only 80CCD(2) applies" : "80C, NPS, 80D, donations, etc."}
      icon={SECTION_ICONS.deductions}
    >
      <div className="form-stack">
        <div className="form-stack__note">
          <strong>80C (max ₹1.5L)</strong> — Auto-filled with Employee PF: <span className="form-stack__amt">{fmt(pfEmployeeAnnual, { compact: true })}/yr</span>.
          Add ELSS, LIC, PPF, school fees etc. below. Total used: <span className="form-stack__amt">{fmt(Math.min(sec80CUsed, 150000), { compact: true })}/{fmt(150000, { compact: true })}</span>
        </div>

        <SliderInput
          label="80C (other than PF)"
          value={state.deductions.c80 / 12}
          onChange={(v) => updateDed("c80", v * 12)}
          min={0}
          max={150000 / 12}
          step={500}
          disabled={dim}
          hint="ELSS, LIC, PPF, school fees, home loan principal. PF already counted."
        />
        <SliderInput
          label="80CCD(1B) — NPS own"
          value={state.deductions.nps80CCD1B / 12}
          onChange={(v) => updateDed("nps80CCD1B", v * 12)}
          min={0}
          max={50000 / 12}
          step={100}
          disabled={dim}
          hint="Extra ₹50K over 80C. Only NPS Tier-I."
        />
        <SliderInput
          label="80CCD(2) — Employer NPS"
          value={state.deductions.empNPS80CCD2 / 12}
          onChange={(v) => updateDed("empNPS80CCD2", v * 12)}
          min={0}
          max={Math.max(50000, empNPSCap / 12)}
          step={100}
          hint={`Up to 14% of Basic = ${fmt(empNPSCap, { compact: true })}/yr. Works in BOTH regimes.`}
        />
        <SliderInput
          label="80D — Health Insurance"
          value={state.deductions.d80 / 12}
          onChange={(v) => updateDed("d80", v * 12)}
          min={0}
          max={100000 / 12}
          step={100}
          disabled={dim}
          hint="Self+family ₹25K, parents ₹25K (₹50K if senior)."
        />
        <SliderInput
          label="80E — Education Loan Interest"
          value={state.deductions.e80 / 12}
          onChange={(v) => updateDed("e80", v * 12)}
          min={0}
          max={500000 / 12}
          step={500}
          disabled={dim}
          hint="No upper limit. Available 8 yrs."
        />
        <SliderInput
          label="80G — Donations"
          value={state.deductions.g80 / 12}
          onChange={(v) => updateDed("g80", v * 12)}
          min={0}
          max={500000 / 12}
          step={500}
          disabled={dim}
          hint="50% or 100% depending on charity."
        />
        <SliderInput
          label="80TTA — Savings interest"
          value={state.deductions.tta80 / 12}
          onChange={(v) => updateDed("tta80", v * 12)}
          min={0}
          max={10000 / 12}
          step={50}
          disabled={dim}
          hint="Max ₹10K/yr."
        />
        <SliderInput
          label="80DD / 80DDB / 80U / 80GG / Other"
          value={(state.deductions.dd80 + state.deductions.ddb80 + state.deductions.u80 + state.deductions.gg80 + state.deductions.other) / 12}
          onChange={(v) => updateDed("other", v * 12)}
          min={0}
          max={300000 / 12}
          step={500}
          disabled={dim}
          hint="Lump entry for less-common deductions."
        />
      </div>
    </AccordionSection>
  );
}

function OtherIncomeSection({ state, setState }) {
  return (
    <AccordionSection
      id="income"
      title="Other Income"
      subtitle="Interest, rental, house property"
      icon={SECTION_ICONS.income}
    >
      <div className="form-stack">
        <SliderInput
          label="Other income (interest, rental)"
          value={state.otherIncome / 12}
          onChange={(v) => setState(s => ({ ...s, otherIncome: v * 12 }))}
          min={0}
          max={1000000 / 12}
          step={500}
          hint="FD interest, savings interest, rental income (minus 30% std). Annual amount."
        />
        <SliderInput
          label="House property loan interest"
          value={state.housePropertyInterest / 12}
          onChange={(v) => setState(s => ({ ...s, housePropertyInterest: v * 12 }))}
          min={0}
          max={200000 / 12}
          step={500}
          disabled={state.regime === "new"}
          hint="Max ₹2L/yr (self-occupied). Old regime only — disabled in new regime."
        />
      </div>
    </AccordionSection>
  );
}

function ComingSoonSection() {
  const features = [
    {
      icon: "⚖️",
      title: "Offer Comparison",
      desc: "Compare two job offers side by side. See the real take-home difference after tax, PF, and regime.",
    },
    {
      icon: "📈",
      title: "Hike Calculator",
      desc: "Get a 20% raise? See exactly how much more lands in your account after all deductions.",
    },
    {
      icon: "🏦",
      title: "Budget Planner",
      desc: "Map your take-home to EMIs, rent, SIPs, and lifestyle goals. Know if your salary is enough.",
    },
    {
      icon: "📊",
      title: "Equity & RSU Deep Dive",
      desc: "Model your ESOP vesting schedule, perquisite tax at exercise, and actual post-tax value.",
    },
    {
      icon: "🗓️",
      title: "Financial Planning",
      desc: "House, retirement, education fund — see the timeline from your current take-home.",
    },
    {
      icon: "💡",
      title: "Investment Ideas",
      desc: "Curated ideas to put your surplus to work. Ranked by tax impact, filtered for your bracket.",
    },
    {
      icon: "🏙️",
      title: "City Cost Adjust",
      desc: "Same CTC, Mumbai vs Bengaluru vs Pune. Real purchasing power after rent and local costs.",
    },
    {
      icon: "🤝",
      title: "Counter-offer Builder",
      desc: "Negotiate smarter. Know your market rate and build a data-backed counter-offer.",
    },
  ];

  return (
    <div className="coming-soon-section">
      <div className="coming-soon-section__head">
        <div className="coming-soon-section__eyebrow">What's coming</div>
        <h2 className="coming-soon-section__title">More tools to understand your money</h2>
        <p className="coming-soon-section__desc">myinhand is building a complete salary intelligence platform for India. Here's what's on the roadmap.</p>
      </div>
      <div className="coming-soon-grid">
        {features.map((f, i) => (
          <div key={i} className="coming-soon-card">
            <div className="coming-soon-card__icon">{f.icon}</div>
            <div className="coming-soon-card__title">{f.title}</div>
            <div className="coming-soon-card__desc">{f.desc}</div>
            <div className="coming-soon-card__tag">Coming soon</div>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { CTCSection, OtherDetailsSection, ExemptionsSection, DeductionsSection, OtherIncomeSection, ComingSoonSection });
