/* forms.jsx — per-offering detail + tailored application forms. */
const {
  Icon, Card, Badge, Button, Input, Select, Toggle, Field, SectionLabel,
} = window.GigiMoneyDesignSystem_b54949;

const G = window.GIGI;
const fmt = (n) => G ? G.fmtKES(n) : 'KES ' + Math.round(n).toLocaleString();
const ASSETS = (G ? G.assets : []).filter(a => a.org === 'org_meco');

function Success({ title, body, onBack }) {
  return (
    <div style={{ textAlign: 'center', padding: '8px 0' }}>
      <div style={{ width: 72, height: 72, borderRadius: 20, background: 'var(--accent)', display: 'grid', placeItems: 'center', margin: '0 auto' }}>
        <Icon name="check" size={36} stroke={2.5} style={{ color: 'var(--accent-ink)' }} />
      </div>
      <h2 className="g-num" style={{ fontSize: 24, fontWeight: 700, margin: '18px 0 8px' }}>{title}</h2>
      <p style={{ color: 'var(--ink-2)', fontSize: 14.5, lineHeight: 1.55, margin: '0 0 22px' }}>{body}</p>
      <Button kind="primary" full onClick={onBack}>Back to offers</Button>
    </div>
  );
}

function MoneyOut({ label, value, sub }) {
  return (
    <div style={{ background: 'var(--accent-ink)', color: '#fff', borderRadius: 'var(--r-lg)', padding: 20, textAlign: 'center', marginBottom: 16 }}>
      <div style={{ color: 'var(--pill-ink)', fontSize: 12.5, fontWeight: 600 }}>{label}</div>
      <div className="g-num" style={{ fontSize: 36, fontWeight: 700, margin: '6px 0 4px', letterSpacing: '-.02em' }}>{value}</div>
      {sub && <div style={{ fontSize: 12.5, color: 'rgba(255,255,255,.62)' }}>{sub}</div>}
    </div>
  );
}

// Tile picker (months, fee %, basis)
function Tiles({ options, value, onChange, cols = 4 }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: `repeat(${cols},1fr)`, gap: 10 }}>
      {options.map(o => {
        const on = o.value === value;
        return (
          <div key={o.value} onClick={() => onChange(o.value)} className="g-tap" style={{
            padding: '14px 10px', borderRadius: 'var(--r-md)', textAlign: 'center',
            border: `1.5px solid ${on ? 'var(--accent-ink)' : 'var(--line)'}`, boxShadow: on ? 'var(--shadow)' : 'none',
          }}>
            <div className="g-num" style={{ fontSize: 20, fontWeight: 700 }}>{o.big}</div>
            <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 2 }}>{o.small}</div>
          </div>
        );
      })}
    </div>
  );
}

// ── 3.1 Rent guarantee ─────────────────────────────────────────
function GuaranteeForm({ onBack }) {
  const [assetId, setAssetId] = React.useState(ASSETS[0]?.id);
  const [fee, setFee] = React.useState(7.5);
  const [done, setDone] = React.useState(false);
  const a = ASSETS.find(x => x.id === assetId) || ASSETS[0];
  const rent = a ? (a.verifiedRent || a.configuredRent) : 0;
  const tenantFee = Math.round(rent * fee / 100);
  if (done) return <Success title="Guarantee activated" body={`${a.name} is now protected. Rent is paid on schedule and default becomes a Gigi Money recovery matter.`} onBack={onBack} />;
  return (
    <>
      <Select label="Property" value={assetId} onChange={setAssetId} options={ASSETS.map(x => ({ value: x.id, label: x.name }))} />
      <div style={{ height: 16 }} />
      <Input label="Monthly rent" prefix="KES" mono value={rent.toLocaleString()} hint="Verified from the managed rent roll" />
      <div style={{ height: 16 }} />
      <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--ink-2)', marginBottom: 8 }}>Tenant fee (instead of deposit)</div>
      <Tiles cols={3} value={fee} onChange={setFee} options={[
        { value: 5, big: '5%', small: 'low risk' },
        { value: 7.5, big: '7.5%', small: 'standard' },
        { value: 10, big: '10%', small: 'higher risk' },
      ]} />
      <div style={{ height: 18 }} />
      <Card style={{ boxShadow: 'none', background: 'var(--surface-2)' }}>
        <Field label="Tenant pays (recurring)" value={fmt(tenantFee) + ' /mo'} mono />
        <Field label="Owner guaranteed" value={fmt(rent) + ' /mo'} mono last />
      </Card>
      <div style={{ height: 18 }} />
      <Button kind="accent" icon="shield" full onClick={() => setDone(true)}>Activate guarantee</Button>
    </>
  );
}

// ── 3.2 Rent advance ───────────────────────────────────────────
function AdvanceForm({ onBack }) {
  const [assetId, setAssetId] = React.useState(ASSETS[0]?.id);
  const [months, setMonths] = React.useState(6);
  const [done, setDone] = React.useState(false);
  const a = ASSETS.find(x => x.id === assetId) || ASSETS[0];
  const rent = a ? (a.verifiedRent || a.configuredRent) : 0;
  const gross = rent * months;
  const discount = Math.round(gross * (0.015 * months));   // funding + risk discount
  const net = gross - discount;
  if (done) return <Success title="Advance requested" body={`${fmt(net)} will be disbursed against ${months} months of assigned rent on ${a.name}, usually within 15 minutes of approval.`} onBack={onBack} />;
  return (
    <>
      <Select label="Property" value={assetId} onChange={setAssetId} options={ASSETS.map(x => ({ value: x.id, label: x.name }))} />
      <div style={{ height: 16 }} />
      <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--ink-2)', marginBottom: 8 }}>Months of future rent to assign</div>
      <Tiles value={months} onChange={setMonths} options={[3, 6, 9, 12].map(m => ({ value: m, big: m, small: 'months' }))} />
      <div style={{ height: 18 }} />
      <MoneyOut label="Lump sum today" value={fmt(net)} sub={`${a.name} · ${months} months assigned`} />
      <Card style={{ boxShadow: 'none', background: 'var(--surface-2)' }}>
        <Field label="Gross future rent" value={fmt(gross)} mono />
        <Field label="Discount" value={'– ' + fmt(discount)} mono last />
      </Card>
      <div style={{ height: 18 }} />
      <Button kind="accent" icon="bolt" full onClick={() => setDone(true)}>Request advance</Button>
    </>
  );
}

// ── 3.3 HELOC ──────────────────────────────────────────────────
function HelocForm({ onBack }) {
  const [assetId, setAssetId] = React.useState((ASSETS.find(a => a.value) || ASSETS[0])?.id);
  const [done, setDone] = React.useState(false);
  const a = ASSETS.find(x => x.id === assetId) || ASSETS[0];
  const value = a ? a.value : 0;
  const line = Math.round(value * 0.5);
  if (done) return <Success title="Line of credit opened" body={`A revolving line of up to ${fmt(line)} is available against ${a.name}. Drawdowns are serviced by your verified rent roll.`} onBack={onBack} />;
  return (
    <>
      <Select label="Property (equity)" value={assetId} onChange={setAssetId} options={ASSETS.filter(x => x.value).map(x => ({ value: x.id, label: x.name }))} />
      <div style={{ height: 16 }} />
      <Input label="Estimated value" prefix="KES" mono value={value.toLocaleString()} hint="Confirmed via Ardhi Sasa valuation" />
      <div style={{ height: 18 }} />
      <MoneyOut label="Available credit line" value={fmt(line)} sub={`Up to 50% of equity · ${a.name}`} />
      <Button kind="accent" icon="home" full onClick={() => setDone(true)}>Open line of credit</Button>
    </>
  );
}

// ── 3.4 Credit card ────────────────────────────────────────────
function CreditCardForm({ onBack }) {
  const [assetId, setAssetId] = React.useState((ASSETS.find(a => a.value) || ASSETS[0])?.id);
  const [limit, setLimit] = React.useState(250000);
  const [done, setDone] = React.useState(false);
  const a = ASSETS.find(x => x.id === assetId) || ASSETS[0];
  const lineCap = a ? Math.round(a.value * 0.5) : 0;
  if (done) return <Success title="Card on its way" body={`A Gigi card with a ${fmt(limit)} monthly limit is linked to your equity line on ${a.name}. Spend draws on the HELOC and is serviced by your rent roll.`} onBack={onBack} />;
  return (
    <>
      <Select label="Equity line" value={assetId} onChange={setAssetId} options={ASSETS.filter(x => x.value).map(x => ({ value: x.id, label: x.name }))} />
      <div style={{ height: 16 }} />
      <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--ink-2)', marginBottom: 8 }}>Monthly card limit</div>
      <Tiles cols={3} value={limit} onChange={setLimit} options={[
        { value: 150000, big: '150K', small: 'KES /mo' },
        { value: 250000, big: '250K', small: 'KES /mo' },
        { value: 500000, big: '500K', small: 'KES /mo' },
      ]} />
      <div style={{ height: 18 }} />
      <Card style={{ boxShadow: 'none', background: 'var(--surface-2)' }}>
        <Field label="Linked equity line" value={fmt(lineCap)} mono />
        <Field label="Use for" value="Property & operating expenses" last />
      </Card>
      <div style={{ height: 18 }} />
      <Button kind="accent" icon="box" full onClick={() => setDone(true)}>Issue card</Button>
    </>
  );
}

const FORMS = { rent_guarantee: GuaranteeForm, rent_advance: AdvanceForm, heloc: HelocForm, credit_card: CreditCardForm };

// ── Detail page ────────────────────────────────────────────────
function OfferDetail({ offerId, onBack }) {
  const offer = window.GIGI_OFFERS.find(o => o.id === offerId);
  if (!offer) return null;
  const FormCmp = FORMS[offer.id];
  return (
    <div className="o-wrap g-enter">
      <button className="o-back" onClick={onBack}><Icon name="chevL" size={16} /> All offerings</button>

      <div className="o-hero" style={{ marginBottom: 24 }}>
        <div className="glow" />
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={{ width: 54, height: 54, borderRadius: 15, background: 'rgba(255,255,255,.08)', display: 'grid', placeItems: 'center', color: 'var(--accent)', flexShrink: 0 }}>
            <Icon name={offer.icon} size={28} />
          </div>
          <div>
            <div style={{ fontSize: 11.5, fontWeight: 700, letterSpacing: '.05em', textTransform: 'uppercase', color: 'var(--accent)', marginBottom: 4 }}>{offer.n} · {offer.forWhom}</div>
            <h1 style={{ margin: 0 }}>{offer.title}</h1>
          </div>
        </div>
        <p style={{ marginTop: 16 }}>{offer.blurb}</p>
      </div>

      <div className="o-detail">
        <Card style={{ padding: 26 }}>
          <SectionLabel>Apply</SectionLabel>
          <FormCmp onBack={onBack} />
        </Card>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <Card style={{ background: 'var(--surface-2)', boxShadow: 'none' }}>
            <SectionLabel>How it works</SectionLabel>
            {offer.terms.map((t, i) => <Field key={i} label={t[0]} value={t[1]} last={i === offer.terms.length - 1} />)}
          </Card>
          <Card style={{ display: 'flex', gap: 12 }}>
            <Icon name="info" size={18} style={{ color: 'var(--ink-3)', flexShrink: 0, marginTop: 1 }} />
            <div style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.55 }}>{offer.angle}</div>
          </Card>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { GigiOfferDetail: OfferDetail, GIGI_FORMS: FORMS });
