/* QuoteFlow Prototype · Customer Portal.
   Where a customer accepts their proposal and pays the deposit. Reads/writes
   the same window.QFStore the admin sends proposals into. */
function PortalApp({ onGoAdmin }) {
  const { Card, Button, Badge, StatusBadge, Input, Avatar } = window.QuoteFlowDesignSystem_41788d;
  const store = useStore();
  const [leadId, setLeadId] = React.useState(null);
  const [pay, setPay] = React.useState(false);             // showing the payment form
  const [card, setCard] = React.useState({ name: '', num: '', exp: '', cvc: '' });
  const settings = store.getSettings();
  const lead = leadId ? store.getLead(leadId) : null;

  // ---------- account chooser (stand-in for a magic-link sign-in) ----------
  if (!lead) {
    const leads = store.getLeads();
    return (
      <div style={{ minHeight: '100%', background: 'var(--bg-app)', padding: '40px 24px' }}>
        <div style={{ maxWidth: 560, margin: '0 auto' }}>
          <div style={{ textAlign: 'center', marginBottom: 24 }}>
            <span style={{ display: 'inline-flex', width: 46, height: 46, borderRadius: 'var(--radius-md)', background: 'var(--green-700)', alignItems: 'center', justifyContent: 'center', marginBottom: 12 }}><Icon name="leaf" size={24} color="#fff" /></span>
            <h1 style={{ fontSize: 26 }}>Greenline Energy · Customer portal</h1>
            <p style={{ marginTop: 8, fontSize: 14.5, color: 'var(--text-muted)' }}>Demo sign-in — choose a customer account to open their portal. In production each customer gets a secure magic link by email.</p>
          </div>
          <Card padding={0}>
            {leads.map((l, i) => (
              <button key={l.id} onClick={() => { setLeadId(l.id); setPay(false); }}
                style={{ display: 'flex', alignItems: 'center', gap: 12, width: '100%', padding: '14px 18px', border: 'none', borderBottom: i < leads.length - 1 ? '1px solid var(--slate-100)' : 'none', background: 'transparent', cursor: 'pointer', textAlign: 'left' }}>
                <Avatar name={l.name} size={38} />
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14.5, fontWeight: 600, color: 'var(--text-strong)' }}>{l.name}</div>
                  <div style={{ fontSize: 12.5, color: 'var(--text-muted)' }}>{l.system} · {l.proposal ? (l.proposal.payment ? 'Deposit paid' : l.proposal.status === 'accepted' ? 'Accepted' : 'Proposal ready') : 'Awaiting proposal'}</div>
                </div>
                <Icon name="arrow-right" size={17} color="var(--text-faint)" />
              </button>
            ))}
          </Card>
        </div>
      </div>
    );
  }

  const p = lead.proposal;
  const steps = store.portalSteps(lead);
  const paid = !!(p && p.payment);

  const Header = () => (
    <header style={{ background: 'var(--surface-card)', borderBottom: '1px solid var(--border-default)' }}>
      <div style={{ maxWidth: 980, margin: '0 auto', padding: '14px 24px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
          <span style={{ width: 32, height: 32, borderRadius: 'var(--radius-md)', background: 'var(--green-700)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="leaf" size={17} color="#fff" /></span>
          <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 17, color: 'var(--text-strong)' }}>Greenline Energy</span>
        </div>
        <button onClick={() => setLeadId(null)} style={{ display: 'flex', alignItems: 'center', gap: 6, border: 'none', background: 'none', cursor: 'pointer', fontFamily: 'var(--font-sans)', fontSize: 13, color: 'var(--text-muted)' }}>
          <Avatar name={lead.name} size={26} /> {lead.name.split(' ')[0]} · Sign out
        </button>
      </div>
    </header>
  );

  // ---------- status tracker ----------
  const Tracker = () => (
    <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 2 }}>
      {steps.map((s, i) => (
        <React.Fragment key={i}>
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 7, flex: '0 0 auto', width: 78, textAlign: 'center' }}>
            <span style={{ width: 28, height: 28, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', background: s.done ? 'var(--primary)' : 'var(--surface-card)', border: s.done ? 'none' : '2px solid var(--border-strong)' }}>
              {s.done ? <Icon name="check" size={14} color="#fff" stroke={3} /> : <span style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-faint)' }}>{i + 1}</span>}
            </span>
            <span style={{ fontSize: 11, fontWeight: s.done ? 600 : 400, color: s.done ? 'var(--text-strong)' : 'var(--text-muted)', lineHeight: 1.25 }}>{s.label}</span>
            {s.meta && <span style={{ fontSize: 10, color: 'var(--accent-deep)', fontWeight: 600, lineHeight: 1.2 }}>{s.meta}</span>}
          </div>
          {i < steps.length - 1 && <span style={{ flex: 1, height: 2, background: steps[i + 1].done ? 'var(--primary)' : 'var(--border-default)', marginTop: 13 }} />}
        </React.Fragment>
      ))}
    </div>
  );

  // ---------- action panel (varies by proposal state) ----------
  const cardValid = card.name && card.num.replace(/\s/g, '').length >= 12 && card.exp && card.cvc.length >= 3;
  const ActionPanel = () => {
    if (!p) {
      return (
        <Card padding={24} style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <span style={{ width: 44, height: 44, flex: 'none', borderRadius: 'var(--radius-md)', background: 'var(--surface-sunken)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="clock" size={22} color="var(--text-muted)" /></span>
          <div><div style={{ fontSize: 15, fontWeight: 600, color: 'var(--text-strong)' }}>Your proposal is being prepared</div><div style={{ fontSize: 13.5, color: 'var(--text-muted)', marginTop: 2 }}>Greenline Energy is finalising your quote — you'll get an email when it's ready to review.</div></div>
        </Card>
      );
    }
    if (paid) {
      return (
        <Card padding={24} style={{ display: 'flex', flexDirection: 'column', gap: 12, background: 'var(--green-50)', border: '1px solid var(--green-200)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <span style={{ width: 44, height: 44, flex: 'none', borderRadius: '50%', background: 'var(--accent-deep)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="check" size={24} color="#fff" stroke={2.6} /></span>
            <div><div style={{ fontSize: 16, fontWeight: 700, color: 'var(--green-800)' }}>You're all set — deposit paid</div><div style={{ fontSize: 13.5, color: 'var(--green-800)' }}>We've received your £{p.payment.amount.toLocaleString('en-GB')} deposit (card ····{p.payment.last4}). Greenline will call to book your survey.</div></div>
          </div>
        </Card>
      );
    }
    if (pay) {
      return (
        <Card padding={24} style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 700 }}>Pay your deposit</h3>
            <Badge tone="neutral">Secure · demo</Badge>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', padding: '12px 16px', background: 'var(--surface-sunken)', borderRadius: 'var(--radius-md)' }}>
            <span style={{ fontSize: 13.5, color: 'var(--text-muted)' }}>15% deposit due now</span>
            <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 22, color: 'var(--text-strong)' }}>{gbp(p.deposit)}</span>
          </div>
          <Input label="Name on card" placeholder="Olivia Grant" value={card.name} onChange={e => setCard(Object.assign({}, card, { name: e.target.value }))} />
          <Input label="Card number" placeholder="4242 4242 4242 4242" value={card.num} onChange={e => setCard(Object.assign({}, card, { num: e.target.value }))} />
          <div style={{ display: 'flex', gap: 12 }}>
            <Input label="Expiry" placeholder="12/28" value={card.exp} onChange={e => setCard(Object.assign({}, card, { exp: e.target.value }))} style={{ flex: 1 }} />
            <Input label="CVC" placeholder="123" value={card.cvc} onChange={e => setCard(Object.assign({}, card, { cvc: e.target.value }))} style={{ flex: 1 }} />
          </div>
          <div style={{ display: 'flex', gap: 10 }}>
            <Button variant="ghost" onClick={() => setPay(false)}>Back</Button>
            <Button variant="primary" style={{ flex: 1 }} disabled={!cardValid} iconLeft={<Icon name="lock" size={15} />}
              onClick={() => { store.payDeposit(lead.id, { last4: card.num.replace(/\s/g, '').slice(-4) || '0000' }); setPay(false); window.scrollTo(0, 0); }}>
              Pay {gbp(p.deposit)} deposit
            </Button>
          </div>
          <p style={{ fontSize: 11.5, color: 'var(--text-faint)', margin: 0, textAlign: 'center' }}>Demo only — no card is charged. Use any numbers.</p>
        </Card>
      );
    }
    // proposal sent or accepted (not yet paid)
    const accepted = p.status === 'accepted';
    return (
      <Card padding={24} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 700 }}>{accepted ? 'Proposal accepted' : 'Review your proposal'}</h3>
          <StatusBadge status={accepted ? 'Accepted' : 'Proposal sent'} />
        </div>
        <p style={{ fontSize: 13.5, color: 'var(--text-muted)', lineHeight: 1.5, margin: 0 }}>
          {accepted ? 'Thanks for accepting! Pay your deposit below to secure your install slot.' : 'Greenline Energy has prepared your proposal. Accept it to move forward — then pay a small deposit to book your survey.'}
        </p>
        <div style={{ display: 'flex', gap: 10 }}>
          {!accepted && <Button variant="primary" style={{ flex: 1 }} iconLeft={<Icon name="check" size={16} />} onClick={() => { store.acceptProposal(lead.id); if (!settings.takeDeposits) window.scrollTo(0, 0); }}>Accept proposal</Button>}
          {(accepted || !settings.takeDeposits) && settings.takeDeposits && <Button variant="primary" style={{ flex: 1 }} iconLeft={<Icon name="credit-card" size={16} />} onClick={() => setPay(true)}>Pay deposit ({gbp(p.deposit)})</Button>}
          <Button variant="secondary" iconLeft={<Icon name="download" size={15} />}>PDF</Button>
        </div>
        {!settings.takeDeposits && accepted && <p style={{ fontSize: 12.5, color: 'var(--text-muted)', margin: 0 }}>No deposit required — Greenline will be in touch to book your survey.</p>}
      </Card>
    );
  };

  return (
    <div style={{ minHeight: '100%', background: 'var(--bg-app)' }}>
      <Header />
      <div style={{ maxWidth: 980, margin: '0 auto', padding: '28px 24px 60px' }}>
        <div style={{ marginBottom: 22 }}>
          <h1 style={{ fontSize: 26 }}>Hello {lead.name.split(' ')[0]} 👋</h1>
          <p style={{ fontSize: 14.5, color: 'var(--text-muted)', marginTop: 4 }}>Track your {lead.system} project and complete the next step below.</p>
        </div>

        <Card padding={24} style={{ marginBottom: 18 }}><Tracker /></Card>

        <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1fr) 320px', gap: 22, alignItems: 'start' }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
            <ActionPanel />

            {/* booked appointments */}
            {lead.project && (lead.project.surveyDate || lead.project.installDate) && (
              <Card padding={0}>
                <div style={{ padding: '16px 22px', borderBottom: '1px solid var(--border-default)' }}><h3 style={{ fontFamily: 'var(--font-display)', fontSize: 16, fontWeight: 700 }}>Your appointments</h3></div>
                <div style={{ padding: '6px 22px' }}>
                  {lead.project.surveyDate && (
                    <div style={{ display: 'flex', alignItems: 'center', gap: 13, padding: '14px 0', borderBottom: lead.project.installDate ? '1px solid var(--slate-100)' : 'none' }}>
                      <span style={{ width: 42, height: 42, flex: 'none', borderRadius: 'var(--radius-md)', background: '#CCFBF1', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="ruler" size={20} color="#0F766E" /></span>
                      <div style={{ flex: 1 }}><div style={{ fontSize: 14.5, fontWeight: 600, color: 'var(--text-strong)' }}>Technical survey</div><div style={{ fontSize: 13, color: 'var(--text-muted)' }}>{store.prettyISO(lead.project.surveyDate)}{lead.project.completedAt ? '' : ' · we\u2019ll confirm a time slot'}</div></div>
                      <Icon name={lead.project.installDate || lead.project.completedAt ? 'check-circle' : 'calendar'} size={18} color={lead.project.installDate || lead.project.completedAt ? 'var(--accent-deep)' : 'var(--text-faint)'} />
                    </div>
                  )}
                  {lead.project.installDate && (
                    <div style={{ display: 'flex', alignItems: 'center', gap: 13, padding: '14px 0' }}>
                      <span style={{ width: 42, height: 42, flex: 'none', borderRadius: 'var(--radius-md)', background: '#E0E7FF', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name="wrench" size={20} color="#4338CA" /></span>
                      <div style={{ flex: 1 }}><div style={{ fontSize: 14.5, fontWeight: 600, color: 'var(--text-strong)' }}>Installation</div><div style={{ fontSize: 13, color: 'var(--text-muted)' }}>{lead.project.completedAt ? 'Completed — thank you!' : store.prettyISO(lead.project.installDate)}</div></div>
                      <Icon name={lead.project.completedAt ? 'badge-check' : 'calendar'} size={18} color={lead.project.completedAt ? 'var(--accent-deep)' : 'var(--text-faint)'} />
                    </div>
                  )}
                </div>
              </Card>
            )}

            {/* proposal / quote summary */}
            <Card padding={0}>
              <div style={{ padding: '16px 22px', borderBottom: '1px solid var(--border-default)' }}><h3 style={{ fontFamily: 'var(--font-display)', fontSize: 16, fontWeight: 700 }}>{p ? 'Your proposal' : 'Your saved quote'}</h3></div>
              <div style={{ padding: '4px 22px' }}>
                {(p ? p.items : [{ label: lead.system, sub: 'Estimated', amount: lead.value }]).map((it, i, arr) => (
                  <div key={i} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 16, padding: '13px 0', borderBottom: i < arr.length - 1 ? '1px solid var(--slate-100)' : 'none' }}>
                    <div><div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text-strong)' }}>{it.label}</div><div style={{ fontSize: 12.5, color: 'var(--text-muted)', marginTop: 1 }}>{it.sub}</div></div>
                    <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 15, color: 'var(--text-strong)', whiteSpace: 'nowrap' }}>{gbp(it.amount)}</span>
                  </div>
                ))}
              </div>
              <div style={{ padding: '14px 22px', background: 'var(--surface-sunken)', display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                <span style={{ fontSize: 13, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.04em', color: 'var(--text-muted)' }}>{p ? 'Total' : 'Estimated range'}</span>
                <span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 21, color: 'var(--text-strong)' }}>{p ? gbp(p.total) : gbp(lead.low) + ' – ' + gbp(lead.high)}</span>
              </div>
            </Card>
          </div>

          {/* documents + contact */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
            <Card padding={20}>
              <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 15, fontWeight: 700, marginBottom: 12 }}>Documents</h3>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {[['Your quote summary', 'file-text'], ['Proposal' + (p ? '' : ' (pending)'), 'file-check'], ['Terms & conditions', 'scroll-text']].map((d, i) => (
                  <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 13.5, color: (d[0].indexOf('pending') > -1 ? 'var(--text-faint)' : 'var(--text-body)') }}>
                    <Icon name={d[1]} size={17} color="var(--text-muted)" /><span style={{ flex: 1 }}>{d[0]}</span>
                    {d[0].indexOf('pending') === -1 && <Icon name="download" size={15} color="var(--text-faint)" />}
                  </div>
                ))}
              </div>
            </Card>
            <Card padding={20} style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 15, fontWeight: 700 }}>Your installer</h3>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}><Avatar name={lead.owner === 'Unassigned' ? 'Greenline Energy' : lead.owner} size={36} /><div><div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--text-strong)' }}>{lead.owner === 'Unassigned' ? 'Greenline Energy' : lead.owner}</div><div style={{ fontSize: 12, color: 'var(--text-muted)' }}>01305 123 456</div></div></div>
              <Button variant="secondary" size="sm" fullWidth iconLeft={<Icon name="message-circle" size={15} />}>Message your installer</Button>
            </Card>
          </div>
        </div>
      </div>
    </div>
  );
}
window.PortalApp = PortalApp;
