// Intake form — 4 steps with $ / % toggles and live reconciliation
// Writes directly to Supabase via onSubmit callback in app.jsx
const { useState: useStateF, useMemo: useMemoF } = React;

function num(v) { const n = parseFloat(v); return isNaN(n) ? 0 : n; }

function toDollars(pair, salesPrice) {
  if (!pair || pair.value === '' || pair.value == null) return 0;
  const v = num(pair.value);
  if (pair.mode === '%') return (salesPrice || 0) * v / 100;
  return v;
}

function MoneyPair({ label, required, value, onChange, salesPrice, grossBase, hint, pctPlaceholder, dollarPlaceholder }) {
  const pair = value || { mode: '$', value: '' };
  const base = grossBase != null ? grossBase : salesPrice;
  const calc = toDollars(pair, base);
  const showCalc = pair.mode === '%';
  return (
    <div className="field">
      <label>{label}{required && <span className="req">*</span>}</label>
      <div className="money-stack">
        <div className="money-toggle">
          <button type="button" className={pair.mode === '$' ? 'on' : ''} onClick={() => onChange({ ...pair, mode: '$' })}>$</button>
          <button type="button" className={pair.mode === '%' ? 'on' : ''} onClick={() => onChange({ ...pair, mode: '%' })}>%</button>
        </div>
        <input className="money-input" type="number" inputMode="decimal" step={pair.mode === '%' ? '0.01' : '1'}
          value={pair.value} placeholder={pair.mode === '%' ? (pctPlaceholder || '3.00') : (dollarPlaceholder || '0')}
          onChange={e => onChange({ ...pair, value: e.target.value })} />
        {showCalc && (
          <div>
            <div className="money-calc-label">Calculated</div>
            <div className={'money-calc' + (calc ? '' : ' zero')}>{calc ? '$' + Math.round(calc).toLocaleString() : '$0'}</div>
          </div>
        )}
      </div>
      {hint && <span style={{ fontSize: 11, color: 'var(--ink-3)' }}>{hint}</span>}
    </div>
  );
}

function DollarField({ label, required, value, onChange, hint, placeholder, error }) {
  return (
    <div className="field">
      <label>{label}{required && <span className="req">*</span>}</label>
      <div className="money-stack">
        <div className="money-toggle" style={{ pointerEvents: 'none', opacity: 0.85 }}>
          <button type="button" className="on">$</button>
        </div>
        <input className="money-input" type="number" inputMode="decimal" value={value ?? ''} placeholder={placeholder || '0'} onChange={e => onChange(e.target.value)} />
      </div>
      {error && <span style={{ color: 'var(--danger)', fontSize: 11 }}>{error}</span>}
      {hint && <span style={{ fontSize: 11, color: 'var(--ink-3)' }}>{hint}</span>}
    </div>
  );
}

const SIMPLE_FIELDS = {
  client:       { label: 'Client name(s) as you want them to appear on cards', req: true, placeholder: 'e.g. Ivy & David Weakland' },
  address:      { label: 'Property address', req: true, placeholder: '5875 Kennyhill Drive' },
  type:         { label: 'Client type', kind: 'radio', req: true, options: ['BUYER','SELLER','NEUTRAL'] },
  agent:        { label: 'Lead agent', kind: 'select', req: true, optionsKey: 'agents' },
  partner:      { label: 'Partner agent (optional)', kind: 'select', optionsKey: 'agentsOpt' },
  contractDate: { label: 'Contract date', kind: 'date', req: true },
  closingDate:  { label: 'Closing date', kind: 'date' },
  source:       { label: 'Lead source', kind: 'select', req: true, optionsKey: 'sources' },
  lender:       { label: 'Lender', placeholder: 'Residential Mortgage - Joe Hegedus' },
  title:        { label: 'Title company', placeholder: 'Stewart Title - Amber Golay' },
  gifts:        { label: 'Client gift' },
  notes:        { label: 'Notes / comments', kind: 'textarea' },
  salesPrice:   { label: 'Sales price', kind: 'money', placeholder: '$1,000,000', req: true },
};

const STEPS = [
  { title: 'Client', ids: ['client','address','type'] },
  { title: 'Deal', ids: ['agent','partner','contractDate','closingDate','source'] },
  { title: 'Financials', kind: 'financials' },
];

function FormView({ onSubmit, agents, sources }) {
  const [step, setStep] = useStateF(0);
  const [values, setValues] = useStateF({
    type: 'BUYER',
    grossCommission: { mode: '%', value: '' },
    agentSplit:      { mode: '%', value: '' },
    teamSplit:       { mode: '%', value: '' },
    partnerSplit:    { mode: '%', value: '' },
    referralSplit:   { mode: '%', value: '' },
  });
  const [errors, setErrors] = useStateF({});
  const [submitted, setSubmitted] = useStateF(false);
  const [saving, setSaving] = useStateF(false);

  const opts = { agents, agentsOpt: ['', ...agents], sources };

  function set(id, v) {
    setValues(prev => ({ ...prev, [id]: v }));
    setErrors(prev => ({ ...prev, [id]: null }));
  }

  const salesPrice = num(values.salesPrice);
  const gross = toDollars(values.grossCommission, salesPrice);
  const referralD = toDollars(values.referralSplit, gross);
  const invoiceD = num(values.invoice);
  const netIncome = Math.max(gross - referralD + invoiceD, 0);
  const splitBase = netIncome;
  const teamD = toDollars(values.teamSplit, splitBase);
  const agentD = toDollars(values.agentSplit, splitBase);
  const partnerD = toDollars(values.partnerSplit, splitBase);
  const splitsSum = teamD + agentD + partnerD;
  const delta = splitsSum - splitBase;

  function validateStep() {
    const e = {};
    const cur = STEPS[step];
    if (cur.ids) {
      for (const id of cur.ids) {
        const f = SIMPLE_FIELDS[id];
        if (f?.req && !values[id]) e[id] = 'Required';
      }
    }
    if (cur.kind === 'financials') {
      if (!values.salesPrice) e.salesPrice = 'Required';
      if (!values.grossCommission || values.grossCommission.value === '') e.grossCommission = 'Required';
    }
    setErrors(e);
    return Object.keys(e).length === 0;
  }

  async function next() {
    if (!validateStep()) return;
    if (step < STEPS.length - 1) { setStep(step + 1); return; }

    setSaving(true);
    const payload = {
      ...values,
      salesPrice: salesPrice || null,
      grossCommission: gross || null,
      teamSplit: teamD || null,
      agentSplit: agentD || null,
      partnerSplit: partnerD || null,
      referralSplit: referralD || null,
      invoice: invoiceD || null,
      status: 'ACTIVE',
      submittedAt: new Date().toISOString(),
    };
    await onSubmit(payload);
    setSaving(false);
    setSubmitted(true);
  }

  function renderSimple(id) {
    const f = SIMPLE_FIELDS[id];
    if (!f) return null;
    const err = errors[id];
    const v = values[id] ?? '';
    if (f.kind === 'radio') {
      return (
        <div className="field" key={id}>
          <label>{f.label}{f.req && <span className="req">*</span>}</label>
          <div className="radio-group">
            {f.options.map(o => (
              <button type="button" key={o} className={'radio-pill' + (v === o ? ' on' : '')} onClick={() => set(id, o)}>{o}</button>
            ))}
          </div>
          {err && <span style={{ color: 'var(--danger)', fontSize: 11 }}>{err}</span>}
        </div>
      );
    }
    if (f.kind === 'select') {
      const list = opts[f.optionsKey] || [];
      return (
        <div className="field" key={id}>
          <label>{f.label}{f.req && <span className="req">*</span>}</label>
          <select value={v} onChange={e => set(id, e.target.value)}>
            <option value="">— Select —</option>
            {list.filter(x => x !== '').map(x => <option key={x} value={x}>{x}</option>)}
          </select>
          {err && <span style={{ color: 'var(--danger)', fontSize: 11 }}>{err}</span>}
        </div>
      );
    }
    if (f.kind === 'textarea') {
      return (
        <div className="field" key={id}>
          <label>{f.label}</label>
          <textarea rows="3" value={v} onChange={e => set(id, e.target.value)} placeholder={f.placeholder} />
        </div>
      );
    }
    return (
      <div className="field" key={id}>
        <label>{f.label}{f.req && <span className="req">*</span>}</label>
        <input type={f.kind === 'date' ? 'date' : f.kind === 'money' ? 'number' : 'text'}
          value={v} onChange={e => set(id, e.target.value)} placeholder={f.placeholder} />
        {err && <span style={{ color: 'var(--danger)', fontSize: 11 }}>{err}</span>}
      </div>
    );
  }

  function renderFinancials() {
    return (
      <>
        <DollarField label="Sales price" required value={values.salesPrice} onChange={v => set('salesPrice', v)} placeholder="1,000,000" error={errors.salesPrice} />
        <div className="form-section-title">Commission</div>
        <MoneyPair label="Gross commission" required value={values.grossCommission} onChange={v => set('grossCommission', v)} salesPrice={salesPrice} />
        <MoneyPair label="Referral company (optional)" value={values.referralSplit} onChange={v => set('referralSplit', v)} salesPrice={salesPrice} grossBase={gross} pctPlaceholder="35.00" />
        <DollarField label="Invoice to Locals" value={values.invoice} onChange={v => set('invoice', v)} />
        <div className="field">
          <label>Net income</label>
          <div className="money-stack">
            <div className="money-toggle" style={{ pointerEvents: 'none', opacity: 0.85 }}><button type="button" className="on">$</button></div>
            <div className={'money-calc' + (netIncome ? '' : ' zero')} style={{ width: 160 }}>${Math.round(netIncome).toLocaleString()}</div>
          </div>
        </div>
        <MoneyPair label="Agent split" value={values.agentSplit} onChange={v => set('agentSplit', v)} salesPrice={salesPrice} grossBase={splitBase} />
        <MoneyPair label="Team split" value={values.teamSplit} onChange={v => set('teamSplit', v)} salesPrice={salesPrice} grossBase={splitBase} />
        <MoneyPair label="Partner split" value={values.partnerSplit} onChange={v => set('partnerSplit', v)} salesPrice={salesPrice} grossBase={splitBase} />
        <div className={'reconcile ' + (splitBase === 0 ? '' : Math.abs(delta) < 0.5 ? 'ok' : 'warn')}>
          <div style={{ display: 'flex', gap: 18 }}>
            <div>
              <div style={{ fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--ink-3)', fontWeight: 600 }}>Net income</div>
              <div className="sum">${Math.round(splitBase).toLocaleString()}</div>
            </div>
            <div>
              <div style={{ fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--ink-3)', fontWeight: 600 }}>Splits total</div>
              <div className="sum">${Math.round(splitsSum).toLocaleString()}</div>
            </div>
          </div>
          <div style={{ textAlign: 'right' }}>
            <div style={{ fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--ink-3)', fontWeight: 600 }}>
              {splitBase === 0 ? 'Enter gross commission' : Math.abs(delta) < 0.5 ? 'Balanced' : (delta > 0 ? 'Over by' : 'Short by')}
            </div>
            <div className={'sum delta ' + (Math.abs(delta) < 0.5 ? 'zero' : 'pos')}>
              {splitBase === 0 ? '—' : (Math.abs(delta) < 0.5 ? '✓ $0' : '$' + Math.abs(Math.round(delta)).toLocaleString())}
            </div>
          </div>
        </div>
      </>
    );
  }

  if (submitted) {
    return (
      <div>
        <div className="page-head"><div><h1 className="page-title">New client intake</h1></div></div>
        <div className="form-shell">
          <div className="form-banner"></div>
          <div className="form-head">
            <div className="form-title">✓ Submitted</div>
            <div style={{ color: 'var(--ink-3)', fontSize: 13 }}>Added <strong style={{ color: 'var(--ink-2)' }}>{values.client}</strong> to the tracker. All agents see it immediately.</div>
          </div>
          <div className="form-body">
            <div className="notify-banner">
              <div className="notify-icon" aria-hidden="true">✉</div>
              <div>
                <div className="notify-title">Notification sent to administrator</div>
                <div className="notify-sub">{new Date().toLocaleString('en-US', { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' })}</div>
              </div>
            </div>
            <div style={{ display: 'flex', gap: 10, marginTop: 14 }}>
              <button className="btn btn-primary" onClick={() => {
                setValues({ type: 'BUYER', grossCommission: { mode: '%', value: '' }, agentSplit: { mode: '%', value: '' }, teamSplit: { mode: '%', value: '' }, partnerSplit: { mode: '%', value: '' }, referralSplit: { mode: '%', value: '' } });
                setStep(0); setSubmitted(false);
              }}>Add another</button>
              <button className="btn" onClick={() => window.location.hash = '#dashboard'}>View dashboard</button>
            </div>
          </div>
        </div>
      </div>
    );
  }

  const cur = STEPS[step];
  return (
    <div>
      <div className="page-head">
        <div>
          <h1 className="page-title">New client intake</h1>
          <p className="page-sub">Submissions save directly to the tracker — visible to all agents immediately.</p>
        </div>
      </div>
      <div className="form-shell">
        <div className="form-banner"></div>
        <div className="form-head">
          <div className="form-title">{cur.title}</div>
          <div style={{ color: 'var(--ink-3)', fontSize: 13 }}>Step {step + 1} of {STEPS.length} · Required fields marked with <span style={{ color: 'var(--danger)' }}>*</span></div>
        </div>
        <div className="form-body">
          {cur.kind === 'financials' ? renderFinancials() : cur.ids.map(id => renderSimple(id))}
        </div>
        <div className="form-footer">
          <div className="form-steps">
            {STEPS.map((s, i) => <div key={i} className={'bar' + (i <= step ? ' on' : '')}></div>)}
            <span style={{ marginLeft: 8 }}>{cur.title}</span>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            {step > 0 && <button className="btn" onClick={() => setStep(step - 1)}>Back</button>}
            <button className="btn btn-primary" onClick={next} disabled={saving}>
              {saving ? 'Saving…' : step === STEPS.length - 1 ? 'Submit' : 'Next →'}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
window.FormView = FormView;
