// Calculator form — left column.
// Talks to parent via `state` + `setState`.

const STATES_DATA = window.SCorpEngine.STATES;
const INDUSTRIES_DATA = window.SCorpEngine.INDUSTRIES;
const suggestReasonableSalary = window.SCorpEngine.suggestReasonableSalary;

function Money({ value, onChange, placeholder, step = 1000 }) {
  const [raw, setRaw] = React.useState(value === 0 || value == null ? '' : String(value));
  React.useEffect(() => {
    setRaw(value === 0 || value == null ? '' : String(value));
  }, [value]);
  return (
    <div className="input-money">
      <input
        type="text"
        inputMode="numeric"
        className="input"
        placeholder={placeholder}
        value={raw ? Number(raw).toLocaleString('en-US') : ''}
        onChange={(e) => {
          const stripped = e.target.value.replace(/[^\d]/g, '');
          setRaw(stripped);
          onChange(stripped === '' ? 0 : Number(stripped));
        }}
      />
    </div>
  );
}

function Segmented({ value, onChange, options }) {
  return (
    <div className="segmented" role="tablist">
      {options.map(o => (
        <button
          key={o.value}
          className={value === o.value ? 'active' : ''}
          onClick={() => onChange(o.value)}
          type="button"
        >{o.label}</button>
      ))}
    </div>
  );
}

function Slider({ value, onChange, min, max, step, format }) {
  return (
    <div className="slider-row">
      <input
        type="range"
        min={min} max={max} step={step}
        value={value}
        onChange={(e) => onChange(Number(e.target.value))}
      />
      <span className="slider-value">{format(value)}</span>
    </div>
  );
}

function SectionHead({ num, title, hint }) {
  return (
    <>
      <div className="form-section-head">
        <span className="form-section-num">{num}</span>
        <span className="form-section-title">{title}</span>
      </div>
      {hint && <div className="form-section-hint">{hint}</div>}
    </>
  );
}

function Calculator({ s, set }) {
  const industryRange = INDUSTRIES_DATA[s.industry].range;
  const salaryMin = Math.min(industryRange[0], 20000);
  const salaryMax = Math.max(industryRange[1] + 50000, s.netIncome);
  const suggestion = suggestReasonableSalary(s.industry, s.netIncome);

  // Auto-suggest salary when income/industry changes and user hasn't manually overridden
  React.useEffect(() => {
    if (s._salaryTouched) return;
    set({ salary: suggestion });
  }, [s.industry, s.netIncome]);

  return (
    <div className="form-stack">

      {/* ===== Step 1: business basics ===== */}
      <div className="form-section">
        <SectionHead num="01" title="About your business" />

        <label className="field">
          <div className="field-label">
            <span>Expected net business income (profit)</span>
            <span className="hint">annual</span>
          </div>
          <Money value={s.netIncome} onChange={v => set({ netIncome: v })} placeholder="80,000" />
        </label>

        <label className="field">
          <div className="field-label">
            <span>Current entity type</span>
          </div>
          <Segmented
            value={s.entity}
            onChange={v => set({ entity: v })}
            options={[
              { value: 'sole', label: 'Sole prop' },
              { value: 'smllc', label: 'Single-member LLC' },
              { value: 'mmllc', label: 'Multi-member LLC' },
            ]}
          />
        </label>

        <div className="field-row">
          <label className="field" style={{marginBottom: 0}}>
            <div className="field-label"><span>Industry</span></div>
            <select
              className="select"
              value={s.industry}
              onChange={e => set({ industry: e.target.value, _salaryTouched: false })}
            >
              {Object.entries(INDUSTRIES_DATA).map(([k, v]) => (
                <option key={k} value={k}>{v.name}</option>
              ))}
            </select>
          </label>
          <label className="field" style={{marginBottom: 0}}>
            <div className="field-label"><span>State</span></div>
            <select
              className="select"
              value={s.state}
              onChange={e => set({ state: e.target.value })}
            >
              {Object.entries(STATES_DATA).map(([k, v]) => (
                <option key={k} value={k}>{v.name}</option>
              ))}
            </select>
          </label>
        </div>

        {INDUSTRIES_DATA[s.industry].sstb && (
          <div className="callout" style={{marginTop: 16}}>
            <strong>Heads up — SSTB classification.</strong> The IRS calls this
            a <em>Specified Service Trade or Business</em>. Above ${
              (s.filing === 'mfj' ? 483900 : 241950).toLocaleString()
            } in taxable income, your QBI deduction phases out fast, which
            changes the S-Corp math materially. The calculator handles this.
          </div>
        )}
      </div>

      {/* ===== Step 2: salary ===== */}
      <div className="form-section">
        <SectionHead
          num="02"
          title='Your "reasonable" salary'
          hint='The IRS requires S-Corp owners pay themselves a salary that matches what a similar role at a similar company would earn. Too low invites audits.'
        />

        <label className="field">
          <div className="field-label">
            <span>Proposed annual W-2 salary to yourself</span>
            <span className="hint">suggested ${suggestion.toLocaleString()}</span>
          </div>
          <Slider
            value={s.salary}
            onChange={v => set({ salary: v, _salaryTouched: true })}
            min={salaryMin} max={Math.max(salaryMax, s.salary + 10000)} step={1000}
            format={v => `$${v.toLocaleString()}`}
          />
        </label>

        <div className="callout">
          <strong>Range for {INDUSTRIES_DATA[s.industry].name.toLowerCase()}:</strong>{' '}
          ${industryRange[0].toLocaleString()}–${industryRange[1].toLocaleString()}.
          {' '}A safe rule of thumb is <strong>~60% of net</strong> for service work, less for capital-intensive businesses.
          {' '}
          <a href="#reasonable-comp" style={{color: 'var(--ink)'}}>What "reasonable" means →</a>
        </div>
      </div>

      {/* ===== Step 3: other income ===== */}
      <div className="form-section">
        <SectionHead
          num="03"
          title="Other income"
          hint="Affects how much of the Social Security wage base you've already used."
        />

        <label className="field">
          <div className="field-label">
            <span>W-2 wages from a separate job</span>
            <span className="hint">already paid SS tax on</span>
          </div>
          <Money value={s.otherW2} onChange={v => set({ otherW2: v })} placeholder="0" />
        </label>

        <label className="field">
          <div className="field-label"><span>Filing status</span></div>
          <Segmented
            value={s.filing}
            onChange={v => set({ filing: v })}
            options={[
              { value: 'single', label: 'Single / HoH' },
              { value: 'mfj', label: 'Married jointly' },
            ]}
          />
        </label>
      </div>

      {/* ===== Step 4: benefits ===== */}
      <div className="form-section">
        <SectionHead
          num="04"
          title="Health & retirement"
          hint="These deductions behave differently under each entity type."
        />

        <label className="field">
          <div className="field-label">
            <span>Annual self-employed health insurance premium</span>
            <span className="hint">0 if employer-covered</span>
          </div>
          <Money value={s.healthInsurance} onChange={v => set({ healthInsurance: v })} placeholder="0" />
        </label>

        <label className="field">
          <div className="field-label">
            <span>Retirement contribution (% of comp)</span>
            <span className="hint">{s.retirementPct}%</span>
          </div>
          <Slider
            value={s.retirementPct}
            onChange={v => set({ retirementPct: v })}
            min={0} max={25} step={1}
            format={v => `${v}%`}
          />
        </label>
      </div>

      {/* ===== Step 5: overhead ===== */}
      <div className="form-section">
        <SectionHead
          num="05"
          title="Estimated S-Corp overhead"
          hint="Real annual costs of running an S-Corp on top of the standard LLC. Defaults are typical midpoint figures — adjust to your situation."
        />

        <div className="field-row">
          <label className="field" style={{marginBottom: 0}}>
            <div className="field-label"><span>Payroll service</span></div>
            <Money value={s.payroll} onChange={v => set({ payroll: v })} />
          </label>
          <label className="field" style={{marginBottom: 0}}>
            <div className="field-label"><span>Tax prep (1120-S)</span></div>
            <Money value={s.taxPrep} onChange={v => set({ taxPrep: v })} />
          </label>
        </div>
        <div className="field-row" style={{marginTop: 14}}>
          <label className="field" style={{marginBottom: 0}}>
            <div className="field-label"><span>Registered agent</span></div>
            <Money value={s.registeredAgent} onChange={v => set({ registeredAgent: v })} />
          </label>
          <div style={{
            fontSize: 12, color: 'var(--ink-3)', fontFamily: 'var(--mono)',
            alignSelf: 'end', paddingBottom: 12
          }}>
            + state LLC fee auto-added
          </div>
        </div>
      </div>

    </div>
  );
}

window.Calculator = Calculator;
