// Multi-step supplier registration form
const RegistrationFlow = ({ onCancel, onComplete }) => {
  const [step, setStep] = React.useState(1);
  const [data, setData] = React.useState({
    businesses: [{ legalName: '', tradeLicense: '', vat: '', industry: 'General Trading', city: 'Dubai', country: 'UAE' }],
    contacts: [{ name: '', role: '', email: '', phone: '' }],
    bank: { accountName: '', iban: '', bankName: '', branch: '', swift: '' },
    docs: [
      { type: 'Trade License', file: null, expires: '' },
      { type: 'VAT Certificate', file: null, expires: '' },
      { type: 'Chamber of Commerce', file: null, expires: '' },
      { type: 'Insurance', file: null, expires: '' },
    ],
  });

  const update = (path, value) => setData(d => ({ ...d, [path]: value }));
  const addBusiness = () => update('businesses', [...data.businesses, { legalName: '', tradeLicense: '', vat: '', industry: 'General Trading', city: 'Dubai', country: 'UAE' }]);
  const addContact = () => update('contacts', [...data.contacts, { name: '', role: '', email: '', phone: '' }]);
  const removeBusiness = (i) => update('businesses', data.businesses.filter((_, x) => x !== i));
  const removeContact = (i) => update('contacts', data.contacts.filter((_, x) => x !== i));
  const updateBusiness = (i, k, v) => update('businesses', data.businesses.map((b, x) => x === i ? { ...b, [k]: v } : b));
  const updateContact = (i, k, v) => update('contacts', data.contacts.map((c, x) => x === i ? { ...c, [k]: v } : c));
  const updateDoc = (i, k, v) => update('docs', data.docs.map((d, x) => x === i ? { ...d, [k]: v } : d));
  const addDoc = () => update('docs', [...data.docs, { type: 'Other', file: null, expires: '' }]);

  const steps = [
    { num: 1, label: 'Company' },
    { num: 2, label: 'Contacts' },
    { num: 3, label: 'Bank' },
    { num: 4, label: 'Documents' },
    { num: 5, label: 'Review' },
  ];

  const submit = () => {
    window.showToast({ title: 'Registration submitted', body: 'You\'ll receive an email once Saif Group reviews your application.', icon: 'check' });
    onComplete();
  };

  return (
    <div className="bleed">
      <div style={{ background: 'var(--ink)', color: 'white', padding: '14px 32px', display: 'flex', alignItems: 'center', gap: 12 }}>
        <SaifLogo size={56}/>
        <button className="btn btn-ghost btn-sm" style={{ marginLeft: 'auto', color: 'rgba(255,255,255,0.7)' }} onClick={onCancel}>Save & exit</button>
      </div>
      <div style={{ maxWidth: 880, margin: '0 auto', padding: '40px 32px' }}>
        <div style={{ marginBottom: 8, fontSize: 12, color: 'var(--text-mute)', textTransform: 'uppercase', fontWeight: 600, letterSpacing: '0.06em' }}>Step {step} of 5</div>
        <h1 style={{ fontSize: 28, fontWeight: 600, letterSpacing: '-0.025em', margin: '0 0 6px', color: 'var(--ink)' }}>
          {step === 1 ? 'Tell us about your business' : step === 2 ? 'Who are the key contacts?' : step === 3 ? 'Bank details for payments' : step === 4 ? 'Upload your documents' : 'Review & submit'}
        </h1>
        <p style={{ color: 'var(--text-mute)', margin: '0 0 28px' }}>
          {step === 1 ? 'Add one or more business entities you operate under.' : step === 2 ? 'Add the people who manage this account.' : step === 3 ? 'We pay all suppliers in AED unless agreed otherwise.' : step === 4 ? 'Each document must include an expiration date.' : 'Make sure everything is correct before submitting.'}
        </p>

        <div className="stepper">
          {steps.map((s, i) => (
            <React.Fragment key={s.num}>
              <div className="step" data-state={step === s.num ? 'active' : step > s.num ? 'done' : 'pending'}>
                <div className="step-dot">{step > s.num ? <Icon name="check" size={12}/> : s.num}</div>
                <div className="step-label">{s.label}</div>
              </div>
              {i < steps.length - 1 && <div className="step-line"></div>}
            </React.Fragment>
          ))}
        </div>

        <div className="card">
          <div className="card-body" style={{ padding: 24 }}>
            {step === 1 && data.businesses.map((b, i) => (
              <div key={i} style={{ marginBottom: 24, paddingBottom: 24, borderBottom: i < data.businesses.length - 1 ? '1px solid var(--line-2)' : 'none' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
                  <div style={{ fontWeight: 600, fontSize: 14 }}>Business entity #{i + 1}</div>
                  {data.businesses.length > 1 && <button className="btn btn-sm btn-ghost" onClick={() => removeBusiness(i)}><Icon name="x" size={12}/> Remove</button>}
                </div>
                <div className="form-row form-row-grid">
                  <div><label className="form-label">Legal company name <span className="req">*</span></label><input className="form-control" value={b.legalName} onChange={e => updateBusiness(i, 'legalName', e.target.value)} placeholder="e.g. Northwind Trading LLC"/></div>
                  <div><label className="form-label">Industry</label>
                    <select className="form-control" value={b.industry} onChange={e => updateBusiness(i, 'industry', e.target.value)}>
                      {['General Trading', 'Construction Materials', 'IT Services', 'Logistics', 'Facilities Maintenance', 'Professional Services'].map(x => <option key={x}>{x}</option>)}
                    </select>
                  </div>
                </div>
                <div className="form-row form-row-grid">
                  <div><label className="form-label">Trade License # <span className="req">*</span></label><input className="form-control" value={b.tradeLicense} onChange={e => updateBusiness(i, 'tradeLicense', e.target.value)} placeholder="CN-XXXXXXX"/></div>
                  <div><label className="form-label">VAT (TRN)</label><input className="form-control" value={b.vat} onChange={e => updateBusiness(i, 'vat', e.target.value)} placeholder="100XXXXXXXXXXX3"/></div>
                </div>
                <div className="form-row form-row-grid">
                  <div><label className="form-label">City</label><input className="form-control" value={b.city} onChange={e => updateBusiness(i, 'city', e.target.value)}/></div>
                  <div><label className="form-label">Country</label><input className="form-control" value={b.country} onChange={e => updateBusiness(i, 'country', e.target.value)}/></div>
                </div>
              </div>
            ))}
            {step === 1 && (
              <button className="btn" onClick={addBusiness}><Icon name="plus" size={13}/> Add another business entity</button>
            )}

            {step === 2 && data.contacts.map((c, i) => (
              <div key={i} style={{ marginBottom: 18, paddingBottom: 18, borderBottom: i < data.contacts.length - 1 ? '1px solid var(--line-2)' : 'none' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
                  <div style={{ fontWeight: 600, fontSize: 14 }}>Contact #{i + 1}</div>
                  {data.contacts.length > 1 && <button className="btn btn-sm btn-ghost" onClick={() => removeContact(i)}><Icon name="x" size={12}/> Remove</button>}
                </div>
                <div className="form-row form-row-grid">
                  <div><label className="form-label">Full name <span className="req">*</span></label><input className="form-control" value={c.name} onChange={e => updateContact(i, 'name', e.target.value)}/></div>
                  <div><label className="form-label">Role</label><input className="form-control" value={c.role} onChange={e => updateContact(i, 'role', e.target.value)} placeholder="Director, Finance, Operations…"/></div>
                </div>
                <div className="form-row form-row-grid">
                  <div><label className="form-label">Email <span className="req">*</span></label><input className="form-control" type="email" value={c.email} onChange={e => updateContact(i, 'email', e.target.value)}/></div>
                  <div><label className="form-label">Phone</label><input className="form-control" value={c.phone} onChange={e => updateContact(i, 'phone', e.target.value)} placeholder="+971 …"/></div>
                </div>
              </div>
            ))}
            {step === 2 && (
              <button className="btn" onClick={addContact}><Icon name="plus" size={13}/> Add another contact</button>
            )}

            {step === 3 && (
              <>
                <div className="form-row form-row-grid">
                  <div><label className="form-label">Account name <span className="req">*</span></label><input className="form-control" value={data.bank.accountName} onChange={e => update('bank', { ...data.bank, accountName: e.target.value })}/></div>
                  <div><label className="form-label">Bank name <span className="req">*</span></label><input className="form-control" value={data.bank.bankName} onChange={e => update('bank', { ...data.bank, bankName: e.target.value })} placeholder="Emirates NBD, ADCB, Mashreq…"/></div>
                </div>
                <div className="form-row">
                  <label className="form-label">IBAN <span className="req">*</span></label>
                  <input className="form-control text-mono" value={data.bank.iban} onChange={e => update('bank', { ...data.bank, iban: e.target.value })} placeholder="AE07 0331 2345 6789 1011 00"/>
                </div>
                <div className="form-row form-row-grid">
                  <div><label className="form-label">Branch</label><input className="form-control" value={data.bank.branch} onChange={e => update('bank', { ...data.bank, branch: e.target.value })}/></div>
                  <div><label className="form-label">SWIFT / BIC</label><input className="form-control text-mono" value={data.bank.swift} onChange={e => update('bank', { ...data.bank, swift: e.target.value })} placeholder="EBILAEAD"/></div>
                </div>
                <div style={{ padding: 12, background: 'var(--surface-2)', borderRadius: 8, fontSize: 12, color: 'var(--text-mute)', display: 'flex', gap: 10 }}>
                  <Icon name="alert" size={14}/>
                  Bank details are encrypted and only visible to authorized finance staff.
                </div>
              </>
            )}

            {step === 4 && (
              <>
                {data.docs.map((d, i) => (
                  <div key={i} style={{ display: 'grid', gridTemplateColumns: '1fr 200px 36px', gap: 12, alignItems: 'flex-end', marginBottom: 14, paddingBottom: 14, borderBottom: '1px solid var(--line-2)' }}>
                    <div>
                      <label className="form-label">{d.type} {['Trade License', 'VAT Certificate'].includes(d.type) && <span className="req">*</span>}</label>
                      <button className="btn full" style={{ justifyContent: 'flex-start', padding: '10px 12px', borderStyle: 'dashed' }}
                        onClick={() => updateDoc(i, 'file', `${d.type.replace(/ /g, '-')}.pdf`)}>
                        <Icon name="upload" size={14}/>
                        {d.file ? <span className="text-mono text-xs">{d.file}</span> : <span className="text-mute">Click to upload PDF/JPG (max 10MB)</span>}
                      </button>
                    </div>
                    <div>
                      <label className="form-label">Expires <span className="req">*</span></label>
                      <input className="form-control" type="date" value={d.expires} onChange={e => updateDoc(i, 'expires', e.target.value)}/>
                    </div>
                    <button className="icon-btn" style={{ color: 'var(--text-mute)', alignSelf: 'flex-end', marginBottom: 1 }}><Icon name="x" size={14}/></button>
                  </div>
                ))}
                <button className="btn" onClick={addDoc}><Icon name="plus" size={13}/> Add another document</button>
              </>
            )}

            {step === 5 && (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
                <div>
                  <div style={{ fontSize: 12, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--text-mute)', marginBottom: 8 }}>Business{data.businesses.length > 1 ? 'es' : ''}</div>
                  {data.businesses.map((b, i) => (
                    <div key={i} style={{ padding: 12, background: 'var(--surface-2)', borderRadius: 8, marginBottom: 8, fontSize: 13 }}>
                      <div style={{ fontWeight: 600 }}>{b.legalName || '— not set —'}</div>
                      <div className="text-mute text-xs mt-4">{b.industry} · {b.city}, {b.country} · TL <span className="text-mono">{b.tradeLicense || '—'}</span></div>
                    </div>
                  ))}
                </div>
                <div>
                  <div style={{ fontSize: 12, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--text-mute)', marginBottom: 8 }}>Contacts ({data.contacts.length})</div>
                  {data.contacts.map((c, i) => (
                    <div key={i} style={{ padding: 12, background: 'var(--surface-2)', borderRadius: 8, marginBottom: 8, fontSize: 13 }}>
                      <div style={{ fontWeight: 600 }}>{c.name || '— not set —'} <span style={{ fontWeight: 400, color: 'var(--text-mute)' }}>· {c.role || 'no role'}</span></div>
                      <div className="text-mute text-xs mt-4">{c.email || 'no email'} · {c.phone || 'no phone'}</div>
                    </div>
                  ))}
                </div>
                <div>
                  <div style={{ fontSize: 12, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--text-mute)', marginBottom: 8 }}>Bank</div>
                  <div style={{ padding: 12, background: 'var(--surface-2)', borderRadius: 8, fontSize: 13 }}>
                    <div style={{ fontWeight: 600 }}>{data.bank.bankName || '— bank name —'}</div>
                    <div className="text-mute text-xs mt-4 text-mono">{data.bank.iban || 'IBAN not set'}</div>
                  </div>
                </div>
                <div>
                  <div style={{ fontSize: 12, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--text-mute)', marginBottom: 8 }}>Documents ({data.docs.filter(d => d.file).length} of {data.docs.length} uploaded)</div>
                  {data.docs.map((d, i) => (
                    <div key={i} style={{ display: 'flex', justifyContent: 'space-between', padding: '8px 12px', background: 'var(--surface-2)', borderRadius: 8, marginBottom: 4, fontSize: 13 }}>
                      <span>{d.type}</span>
                      <span className="text-mute text-xs">{d.file ? <><Icon name="check" size={11}/> uploaded · expires {d.expires || '—'}</> : '— missing —'}</span>
                    </div>
                  ))}
                </div>
                <label style={{ display: 'flex', gap: 8, alignItems: 'flex-start', fontSize: 12, color: 'var(--text-mute)', marginTop: 8 }}>
                  <input type="checkbox" defaultChecked style={{ marginTop: 2 }}/>
                  I confirm that all information provided is accurate. Saif Al Khyeli Group may verify these details with relevant authorities.
                </label>
              </div>
            )}
          </div>
          <div style={{ padding: '14px 24px', borderTop: '1px solid var(--line-2)', background: 'var(--surface-2)', display: 'flex', justifyContent: 'space-between' }}>
            <button className="btn" onClick={() => step === 1 ? onCancel() : setStep(step - 1)}>
              <Icon name="chevronLeft" size={13}/> {step === 1 ? 'Cancel' : 'Back'}
            </button>
            {step < 5 ? (
              <button className="btn btn-primary" onClick={() => setStep(step + 1)}>Continue <Icon name="arrowRight" size={13}/></button>
            ) : (
              <button className="btn btn-accent" onClick={submit}><Icon name="send" size={13}/> Submit registration</button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

// SUPPLIER PORTAL — supplier-role views
const SupplierHome = () => {
  const { ME_SUPPLIER, SAIF_COMPANIES } = window.SaifData;
  return (
    <div className="page">
      <div className="page-header">
        <div>
          <h1 className="page-title">Welcome back, {ME_SUPPLIER.name.split(' ')[0]}</h1>
          <p className="page-subtitle">{ME_SUPPLIER.company_name} · approved supplier since Mar 2024</p>
        </div>
        <div className="page-actions">
          <Badge kind="green">Active</Badge>
        </div>
      </div>
      <ReminderWidget role="supplier"/>

      <div className="kpi-grid">
        <KPICard label="Open POs" value={3} meta={fmtCurrency(184500) + ' total'} icon="po"/>
        <KPICard label="Documents to renew" value={2} meta="trade license expired" icon="alert"/>
        <KPICard label="Pending tasks" value={1} meta="from Saif Trading" icon="inbox"/>
        <KPICard label="Engaged with" value={2} meta="group companies" icon="building"/>
      </div>

      <div className="dash-grid">
        <div className="card">
          <div className="card-header"><h3 className="card-title">Action items from Saif Al Khyeli Group</h3></div>
          <div>
            {[
              { title: 'Upload renewed trade license', desc: 'Your TL expired 11 Mar 2026', co: 'trd', urgent: true, due: '2 days' },
              { title: 'Confirm receipt — PO-2026-0405', desc: 'Industrial fasteners delivery', co: 'trd', urgent: false, due: '5 days' },
              { title: 'Review updated payment terms', desc: 'Moving to NET-45 from Q3', co: 'hld', urgent: false, due: '10 days' },
            ].map((t, i) => {
              const co = SAIF_COMPANIES.find(c => c.id === t.co);
              return (
                <div key={i} className="task-row" style={{ gridTemplateColumns: '1fr 100px 80px' }}>
                  <div>
                    <div className="task-title">{t.title}</div>
                    <div className="task-meta">
                      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}><span className="company-dot" style={{ background: co.color, width: 6, height: 6, borderRadius: '50%' }}></span> {co.name}</span>
                      <span className="dot-sep">{t.desc}</span>
                    </div>
                  </div>
                  {t.urgent ? <Badge kind="red">Urgent</Badge> : <Badge kind="blue">Open</Badge>}
                  <span className="text-mono text-xs text-mute">{t.due}</span>
                </div>
              );
            })}
          </div>
        </div>

        <div className="card">
          <div className="card-header"><h3 className="card-title">Your documents</h3></div>
          <div className="card-body" style={{ padding: 0 }}>
            {[
              { type: 'Trade License', exp: '2026-03-11', status: 'red' },
              { type: 'VAT Certificate', exp: '2027-03-11', status: 'green' },
              { type: 'Chamber of Commerce', exp: '2026-06-15', status: 'amber' },
              { type: 'Insurance', exp: '2026-10-01', status: 'green' },
            ].map((d, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 18px', borderBottom: '1px solid var(--line-2)' }}>
                <Icon name="file" size={16} className="text-mute"/>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 500 }}>{d.type}</div>
                  <div style={{ fontSize: 11, color: 'var(--text-mute)' }}>Expires {fmtDate(d.exp)}</div>
                </div>
                <DocPill status={d.status}>{d.status === 'red' ? 'Renew' : d.status === 'amber' ? 'Soon' : 'Valid'}</DocPill>
              </div>
            ))}
            <div style={{ padding: 12 }}>
              <button className="btn full" style={{ justifyContent: 'center' }}><Icon name="upload" size={13}/> Upload new document</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { RegistrationFlow, SupplierHome });
