/* global React, window, Icon, PageHead, Tag, ScoreBadge, CHART, LEADS, QA_CATS */
/* ============================================================
   Leads / CRM — inbox + lead capture landing preview
   ============================================================ */
const { useState: useLD } = React;

const SCORE_TONE = { Hot: 'clay', Warm: 'amber', Cold: 'green' };

function LeadInbox({ openLead }) {
  const counts = { all: LEADS.length, Hot: LEADS.filter((l) => l.score === 'Hot').length, today: 5 };
  return (
    <div className="fade-up" style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 16, alignItems: 'start' }}>
      <div className="card" style={{ overflow: 'hidden' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '12px var(--card-pad)', borderBottom: '1px solid var(--line)' }}>
          {[['All', counts.all], ['Hot', counts.Hot], ['New today', counts.today]].map(([l, n], i) => (
            <button key={l} className="chip" data-on={i === 0}>{l} <b style={{ marginLeft: 2 }}>{n}</b></button>
          ))}
          <div style={{ flex: 1 }} />
          <button className="btn btn-quiet" style={{ fontSize: 12 }}><Icon name="download" size={14} />Export</button>
        </div>
        {LEADS.map((l) => (
          <button key={l.id} onClick={() => openLead(l)} style={{
            display: 'grid', gridTemplateColumns: '34px 1.4fr 2fr 1fr auto', alignItems: 'center', gap: 14,
            width: '100%', textAlign: 'left', border: 'none', borderBottom: '1px solid var(--line-2)', cursor: 'pointer',
            background: 'none', fontFamily: 'inherit', color: 'var(--ink)', padding: '13px var(--card-pad)',
          }}>
            <div style={{ width: 34, height: 34, borderRadius: 999, background: 'var(--panel-2)', border: '1px solid var(--line)', display: 'grid', placeItems: 'center', fontSize: 12.5, fontWeight: 700, color: 'var(--ink-2)' }}>{l.name.split(' ').map((n) => n[0]).join('')}</div>
            <div>
              <div style={{ fontSize: 13.5, fontWeight: 700 }}>{l.name}</div>
              <div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{l.src} · {l.lang}</div>
            </div>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>{l.intent.map((t) => <Tag key={t} color={QA_CATS[t]}>{t}</Tag>)}</div>
            <div style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{l.time}</div>
            <ScoreBadge tone={SCORE_TONE[l.score]}>{l.score}</ScoreBadge>
          </button>
        ))}
      </div>

      {/* funnel summary */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        <div className="card" style={{ padding: 'var(--card-pad)' }}>
          <h3 style={{ margin: '0 0 14px', fontSize: 14.5, fontWeight: 700 }}>This week's funnel</h3>
          {[['Live viewers', 184, 1], ['QR scans', 96, 0.52], ['Form submits', 41, 0.22], ['Booked consults', 12, 0.065]].map(([l, n, w]) => (
            <div key={l} style={{ marginBottom: 12 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12.5, marginBottom: 5 }}><span style={{ fontWeight: 600 }}>{l}</span><span className="tabnum" style={{ fontWeight: 800 }}>{n}</span></div>
              <div style={{ height: 8, background: 'var(--panel-2)', borderRadius: 999, overflow: 'hidden' }}><div style={{ width: (w * 100) + '%', height: '100%', background: CHART.green, borderRadius: 999 }} /></div>
            </div>
          ))}
        </div>
        <div className="card" style={{ padding: 'var(--card-pad)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}><Icon name="sparkles" size={15} color="var(--accent)" /><h3 style={{ margin: 0, fontSize: 14, fontWeight: 700 }}>AI next steps</h3></div>
          {['给 Jennifer Liu 发 Aurora 独立屋月报', '为 David Chen 启动 CMA 估值流程', '邀请 5 位 First-Time 买家参加下场直播'].map((t, i) => (
            <div key={i} style={{ display: 'flex', gap: 9, padding: '9px 0', borderTop: i ? '1px solid var(--line)' : 'none', fontSize: 12.5, lineHeight: 1.45 }}>
              <Icon name="check" size={15} color="var(--accent)" style={{ marginTop: 1, flexShrink: 0 }} />{t}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function LeadProfile({ lead, back }) {
  return (
    <div className="fade-up" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, alignItems: 'start' }}>
      <div style={{ gridColumn: '1 / -1' }}>
        <button className="btn btn-quiet" onClick={back} style={{ fontSize: 12.5 }}><Icon name="chevronL" size={15} />Back to inbox</button>
      </div>
      <div className="card" style={{ padding: 'var(--card-pad)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 16 }}>
          <div style={{ width: 52, height: 52, borderRadius: 999, background: 'var(--az-dark-green,#1F281F)', color: '#fff', display: 'grid', placeItems: 'center', fontSize: 18, fontWeight: 700 }}>{lead.name.split(' ').map((n) => n[0]).join('')}</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 18, fontWeight: 700 }}>{lead.name}</div>
            <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{lead.src} · {lead.lang} · {lead.time}</div>
          </div>
          <ScoreBadge tone={SCORE_TONE[lead.score]}>{lead.score}</ScoreBadge>
        </div>
        <div className="eyebrow" style={{ marginBottom: 8 }}>Intent tags</div>
        <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 18 }}>{lead.intent.map((t) => <Tag key={t} color={QA_CATS[t]}>{t}</Tag>)}<Tag>Budget $1.5–1.8M</Tag><Tag>Timeline 3–6 mo</Tag></div>
        <div className="eyebrow" style={{ marginBottom: 8 }}>Activity</div>
        {[['Submitted live report form', '2 min ago'], ['Watched Spring Market Outlook', '40 min ago'], ['Downloaded York April report', '2 days ago']].map(([t, w], i) => (
          <div key={i} style={{ display: 'flex', gap: 10, padding: '9px 0', borderTop: i ? '1px solid var(--line)' : '1px solid var(--line)' }}>
            <span style={{ width: 7, height: 7, borderRadius: 999, background: CHART.green, marginTop: 5 }} />
            <div style={{ flex: 1, fontSize: 12.5 }}>{t}</div><div style={{ fontSize: 11, color: 'var(--ink-3)' }}>{w}</div>
          </div>
        ))}
      </div>
      <div className="card" style={{ padding: 'var(--card-pad)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}><Icon name="sparkles" size={15} color="var(--accent)" /><h3 style={{ margin: 0, fontSize: 14.5, fontWeight: 700 }}>AI recommended next step</h3></div>
        <div className="card" style={{ background: 'var(--panel-2)', padding: 14, marginBottom: 14 }}>
          <div style={{ fontSize: 13, lineHeight: 1.6 }}>{lead.name.split(' ')[0]} 在看 Aurora 独立屋，预算 $1.5–1.8M。建议发送 <b>Aurora Detached 月报</b> + 3 套符合条件的在售房源，并邀请预约看房。</div>
        </div>
        <div style={{ display: 'flex', gap: 9, marginBottom: 18 }}>
          <button className="btn btn-primary" style={{ flex: 1, justifyContent: 'center' }}><Icon name="send" size={14} />Send report</button>
          <button className="btn btn-ghost" style={{ flex: 1, justifyContent: 'center' }}><Icon name="clock" size={14} />Schedule task</button>
        </div>
        <div className="eyebrow" style={{ marginBottom: 8 }}>Follow-up</div>
        {[['Send Aurora report', 'Due today', 'amber'], ['Book viewing call', 'Tomorrow', 'green']].map(([t, d, tone], i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 0', borderTop: '1px solid var(--line)' }}>
            <span style={{ width: 16, height: 16, borderRadius: 4, border: '1.5px solid var(--line)' }} />
            <div style={{ flex: 1, fontSize: 12.5, fontWeight: 600 }}>{t}</div>
            <ScoreBadge tone={tone}>{d}</ScoreBadge>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ---- Lead capture landing (phone) ---- */
function LandingPreview() {
  const [done, setDone] = useLD(false);
  return (
    <div className="fade-up" style={{ display: 'grid', gridTemplateColumns: '1fr 360px', gap: 28, alignItems: 'start' }}>
      <div className="card" style={{ padding: 'var(--card-pad)' }}>
        <h3 style={{ margin: '0 0 6px', fontSize: 15, fontWeight: 700 }}>Lead capture — landing page</h3>
        <p style={{ fontSize: 12.5, color: 'var(--ink-2)', margin: '0 0 16px', lineHeight: 1.6 }}>This is what viewers see when they scan the live QR code. Low friction, strong CTA, privacy note. Submitting auto-tags the lead and routes it to the Inbox.</p>
        <div className="eyebrow" style={{ marginBottom: 8 }}>Capture entry points</div>
        {[['Get this live\'s report', 'Live Lead', 'reports'], ['Check my home value', 'Seller Lead → CMA', 'cma'], ['Monthly region report', 'Subscribe', 'chart'], ['Book a consultation', 'Follow-up task', 'leads']].map(([t, tag, ic], i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 0', borderTop: '1px solid var(--line)' }}>
            <div style={{ width: 32, height: 32, borderRadius: 7, background: 'var(--panel-2)', border: '1px solid var(--line)', display: 'grid', placeItems: 'center', color: 'var(--accent)' }}><Icon name={ic} size={16} /></div>
            <div style={{ flex: 1 }}><div style={{ fontSize: 13, fontWeight: 700 }}>{t}</div><div style={{ fontSize: 11, color: 'var(--ink-3)' }}>Tag · {tag}</div></div>
            <Icon name="chevronR" size={16} color="var(--ink-3)" />
          </div>
        ))}
      </div>

      {/* phone */}
      <div style={{ background: 'var(--az-dark-green,#1F281F)', borderRadius: 34, padding: 12, boxShadow: 'var(--shadow-lg,0 16px 40px rgba(31,40,31,0.14))' }}>
        <div style={{ background: '#fff', borderRadius: 24, overflow: 'hidden', minHeight: 600, display: 'flex', flexDirection: 'column' }}>
          <div style={{ background: '#1F281F', padding: '18px 22px 22px', color: '#fff' }}>
            <img src="assets/az-logo-horizontal-white.png" alt="AZ" style={{ height: 18, marginBottom: 16 }} />
            <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '0.12em', textTransform: 'uppercase', color: CHART.green, marginBottom: 8 }}>Spring Market Outlook</div>
            <div style={{ fontSize: 20, fontWeight: 800, lineHeight: 1.25, color: '#fff' }}>获取本场直播的<br/>York 市场报告</div>
          </div>
          <div style={{ padding: 22, flex: 1, display: 'flex', flexDirection: 'column', gap: 13 }}>
            {done ? (
              <div style={{ textAlign: 'center', margin: 'auto 0', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12 }}>
                <div style={{ width: 56, height: 56, borderRadius: 999, background: 'rgba(100,188,100,0.16)', display: 'grid', placeItems: 'center' }}><Icon name="check" size={28} color={CHART.green} /></div>
                <div style={{ fontSize: 17, fontWeight: 700, color: '#1F281F' }}>报告已在路上</div>
                <div style={{ fontSize: 13, color: '#585858', lineHeight: 1.55 }}>我们会把 York 4月市场报告发到你的邮箱，并根据你的关注区域推送月报。</div>
                <button className="btn btn-ghost" onClick={() => setDone(false)} style={{ marginTop: 8 }}>Reset preview</button>
              </div>
            ) : (
              <>
                {[['关注区域 Region', 'Aurora'], ['姓名 Name', ''], ['电话 Phone', ''], ['邮箱 Email', '']].map(([l, v]) => (
                  <label key={l} style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
                    <span style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase', color: '#585858' }}>{l}</span>
                    <input className="in" defaultValue={v} placeholder={l.split(' ')[1]} style={{ padding: '11px 12px', color: '#1F281F', background: '#fff' }} />
                  </label>
                ))}
                <div style={{ display: 'flex', gap: 8 }}>
                  {['Buyer', 'Seller', 'Investor'].map((t, i) => <span key={t} className="chip" data-on={i === 0} style={{ flex: 1, justifyContent: 'center', color: '#1F281F' }}>{t}</span>)}
                </div>
                <button className="btn btn-primary" onClick={() => setDone(true)} style={{ justifyContent: 'center', padding: 13, marginTop: 4 }}>获取报告 →</button>
                <div style={{ fontSize: 10.5, color: '#969696', textAlign: 'center', lineHeight: 1.5 }}>数据仅用于发送报告与跟进，不会分享给第三方。Data from TRREB Market Watch · 仅供参考。</div>
              </>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

function Leads({ }) {
  const [tab, setTab] = useLD('inbox');
  const [lead, setLead] = useLD(null);
  return (
    <div className="fade-up" style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <PageHead eyebrow="Leads / CRM" title={lead ? 'Lead profile' : 'Lead inbox'}
        sub={lead ? null : '扫码用户自动进入这里，并按关注区域和需求打标签。'}
        actions={!lead &&
          <div style={{ display: 'inline-flex', background: 'var(--panel-2)', border: '1px solid var(--line)', borderRadius: 7, padding: 3, gap: 2 }}>
            {[['inbox', 'Inbox'], ['landing', 'Capture page']].map(([v, l]) => (
              <button key={v} onClick={() => setTab(v)} style={{ border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 12.5, fontWeight: 700, padding: '7px 13px', borderRadius: 5, background: tab === v ? 'var(--accent)' : 'transparent', color: tab === v ? '#16241B' : 'var(--ink-2)' }}>{l}</button>
            ))}
          </div>
        } />
      {lead ? <LeadProfile lead={lead} back={() => setLead(null)} />
        : tab === 'inbox' ? <LeadInbox openLead={setLead} /> : <LandingPreview />}
    </div>
  );
}
window.Leads = Leads;
