// Customer Portal — portal link management · customer view simulation

function CustomerPortal({ deals, contacts, showToast }) {
  const toast = showToast || (() => {});
  const LIVE = !!window.STAGEVO_AUTHED && !!window.StagevoData;
  const [activeTab, setActiveTab] = React.useState('manage');
  const [selectedDeal, setSelectedDeal] = React.useState(
    deals.filter(d => d.stage !== 'lost')[0]
  );
  const [portalEnabled, setPortalEnabled] = React.useState(true);
  const [notifyOnStage, setNotifyOnStage] = React.useState(true);
  const [notifyOnDoc, setNotifyOnDoc] = React.useState(true);
  const [showQR, setShowQR] = React.useState(false);
  const [portalLink, setPortalLink] = React.useState(null);
  const [activity, setActivity] = React.useState(null);

  const relTime = (iso) => {
    if (!iso) return ''; const d = new Date(iso); const diff = (Date.now() - d) / 1000;
    if (diff < 3600) return Math.max(1, Math.round(diff/60)) + 'm ago';
    if (diff < 86400) return Math.round(diff/3600) + 'h ago';
    return d.toLocaleDateString('en-AU', { day:'numeric', month:'short' });
  };
  const EVENT_META = {
    viewed:{ icon:'👁️', label:'Customer viewed portal', color:'var(--info-soft)' },
    doc_downloaded:{ icon:'📥', label:'Document downloaded', color:'var(--warn-soft)' },
    doc_signed:{ icon:'✅', label:'Document signed', color:'var(--won-soft)' },
    message_sent:{ icon:'💬', label:'Message sent', color:'var(--accent-soft)' },
    stage_changed:{ icon:'📈', label:'Stage advanced', color:'var(--won-soft)' },
  };

  React.useEffect(() => {
    if (!LIVE || !selectedDeal) return; let alive = true;
    (async () => {
      try {
        const { data: link } = await window.StagevoData.getPortalLink(selectedDeal.id);
        if (!alive) return;
        setPortalLink(link || null);
        setPortalEnabled(!!(link && link.enabled));
        if (link) { const { data: acts } = await window.StagevoData.getPortalActivity(link.id); if (alive) setActivity(acts || []); }
        else setActivity(null);
      } catch (e) {}
    })();
    return () => { alive = false; };
  }, [LIVE, selectedDeal && selectedDeal.id]);

  async function togglePortal() {
    const next = !portalEnabled; setPortalEnabled(next);
    if (LIVE && next && !portalLink && selectedDeal) {
      try {
        const match = (contacts || []).find(c => selectedDeal.contactId ? c.id === selectedDeal.contactId : (c.name || '').toLowerCase() === (selectedDeal.customer || '').toLowerCase());
        const { data: link } = await window.StagevoData.createPortalLink(selectedDeal.id, match ? match.id : null);
        setPortalLink(link || null);
      } catch (e) {}
    }
  }
  const copyLink = () => { try { navigator.clipboard.writeText(portalUrl); } catch (e) {} };

  const PORTAL_STAGES = [
    { id:'enquiry', label:'Enquiry Received', done:true, icon:'📩' },
    { id:'design', label:'Design Appointment', done:true, icon:'📐' },
    { id:'quote', label:'Quote Prepared', done:true, icon:'📄' },
    { id:'approval', label:'Quote Approved', done: selectedDeal?.stage === 'sold', icon:'✍️' },
    { id:'deposit', label:'Deposit Paid', done: selectedDeal?.stage === 'sold', icon:'💳' },
    { id:'production', label:'In Production', done:false, icon:'🔨' },
    { id:'install', label:'Installation', done:false, icon:'🏠' },
    { id:'complete', label:'Complete', done:false, icon:'🎉' },
  ];

  const PORTAL_DOCS = [
    { name:'Kitchen Proposal v2.pdf', type:'quote', date:'11 Jun 2026', signed:false },
    { name:'Site Measurement Checklist.pdf', type:'checklist', date:'8 Jun 2026', signed:true },
    { name:'Design Brief.pdf', type:'brief', date:'5 Jun 2026', signed:false },
  ];

  const PORTAL_MSGS = [
    { from:'designer', name:'Alex Kim', time:'10:42 am', text:'Your updated quote is ready! Please review and sign when you\'re happy. Let me know if you have any questions about the island bench spec.' },
    { from:'customer', name:selectedDeal?.customer?.split(' ')[0] || 'Client', time:'9:15 am', text:'Hi Alex, thanks for the update. Will the waterfall edge be ready in time? We have the builder starting on 28 July.' },
    { from:'designer', name:'Alex Kim', time:'Yesterday', text:'Good news — I\'ve confirmed with the supplier. Lead time is 4–5 weeks, so we\'re on track for your July date.' },
  ];

  const portalUrl = (portalLink && portalLink.token)
    ? `https://app.stagevo.io/portal/${portalLink.token}`
    : `https://app.stagevo.io/portal/${(selectedDeal?.id||'').replace(/\s/g,'-').toLowerCase()}`;

  const DEMO_ACTIVITY = [
    { time:'Today 10:42 am', event:'Customer viewed portal', icon:'👁️', color:'var(--info-soft)' },
    { time:'Today 9:30 am', event:'Designer sent message', icon:'💬', color:'var(--accent-soft)' },
    { time:'Yesterday 3:15 pm', event:'Quote v2.pdf downloaded by customer', icon:'📥', color:'var(--warn-soft)' },
    { time:'Yesterday 11:00 am', event:'Stage advanced to Quote Prepared', icon:'📈', color:'var(--won-soft)' },
    { time:'9 Jun 3:44 pm', event:'Customer replied to message', icon:'💬', color:'var(--accent-soft)' },
    { time:'8 Jun 10:00 am', event:'Site Measurement Checklist signed', icon:'✅', color:'var(--won-soft)' },
    { time:'8 Jun 9:30 am', event:'Portal link first opened by customer', icon:'🔗', color:'var(--info-soft)' },
    { time:'7 Jun 2:00 pm', event:'Portal link sent via email', icon:'📧', color:'var(--surface-2)' },
  ];
  const activityList = (LIVE && activity)
    ? activity.map(a => { const m = EVENT_META[a.event] || { icon:'•', label: a.event, color:'var(--surface-2)' }; return { time: relTime(a.created_at), event: m.label, icon: m.icon, color: m.color }; })
    : DEMO_ACTIVITY;

  return (
    <div>
      {/* Tab bar */}
      <div style={{ display:'flex', gap:2, background:'var(--surface-2)', border:'1px solid var(--border)', borderRadius:8, padding:3, marginBottom:18, width:'fit-content' }}>
        {[['manage','Portal Settings'],['preview','Customer View'],['activity','Activity']].map(([id,label]) => (
          <button key={id} onClick={() => setActiveTab(id)}
            style={{ padding:'5px 16px', borderRadius:6, border:'none', fontSize:13, fontWeight:activeTab===id?600:400,
              background: activeTab===id ? 'var(--surface)' : 'transparent',
              color: activeTab===id ? 'var(--ink)' : 'var(--ink-3)',
              boxShadow: activeTab===id ? 'var(--shadow-sm)' : 'none', cursor:'pointer' }}>
            {label}
          </button>
        ))}
      </div>

      {/* ── MANAGE ── */}
      {activeTab === 'manage' && (
        <div style={{ display:'grid', gridTemplateColumns:'1fr 360px', gap:16 }}>
          <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
            {/* Deal selector */}
            <div className="card card-pad">
              <label style={{ fontSize:11, textTransform:'uppercase', letterSpacing:'0.08em', color:'var(--ink-3)', fontWeight:600, display:'block', marginBottom:8 }}>Select Deal</label>
              <select className="sel" style={{ width:'100%', padding:'8px 12px', border:'1px solid var(--border)', borderRadius:6, fontSize:13, background:'var(--surface-2)' }}
                value={selectedDeal?.id||''} onChange={e => setSelectedDeal(deals.find(d=>d.id===e.target.value))}>
                {deals.filter(d=>d.stage!=='lost').slice(0,12).map(d => (
                  <option key={d.id} value={d.id}>{d.customer} — {d.id}</option>
                ))}
              </select>
            </div>

            {/* Portal toggle + link */}
            <div className="card card-pad">
              <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:16 }}>
                <div>
                  <div style={{ fontSize:14, fontWeight:600, color:'var(--ink)' }}>Customer Portal</div>
                  <div style={{ fontSize:12, color:'var(--ink-3)', marginTop:2 }}>Give {selectedDeal?.customer||'the customer'} a live view of their project</div>
                </div>
                <button onClick={togglePortal}
                  style={{ width:44, height:24, borderRadius:99, border:'none', cursor:'pointer', position:'relative', background: portalEnabled ? 'var(--accent)' : 'var(--border)', transition:'background 0.2s' }}>
                  <span style={{ position:'absolute', top:3, left: portalEnabled ? 23 : 3, width:18, height:18, borderRadius:99, background:'white', boxShadow:'0 1px 3px rgba(0,0,0,0.2)', transition:'left 0.2s' }} />
                </button>
              </div>
              {portalEnabled && (
                <>
                  <div style={{ display:'flex', gap:8, alignItems:'center', marginBottom:12 }}>
                    <div style={{ flex:1, background:'var(--surface-2)', border:'1px solid var(--border)', borderRadius:6, padding:'8px 12px', fontSize:12, color:'var(--ink-3)', fontFamily:'var(--mono)', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{portalUrl}</div>
                    <button className="btn sm" onClick={copyLink}>Copy link</button>
                    <button className="btn sm" onClick={() => setShowQR(p=>!p)}>QR</button>
                  </div>
                  {showQR && (
                    <div style={{ display:'flex', justifyContent:'center', marginBottom:12 }}>
                      <div style={{ width:100, height:100, background:'var(--surface-3)', borderRadius:8, display:'flex', alignItems:'center', justifyContent:'center', fontSize:11, color:'var(--ink-3)', flexDirection:'column', gap:4, border:'1px solid var(--border)' }}>
                        <div style={{ display:'grid', gridTemplateColumns:'repeat(5,12px)', gap:2 }}>
                          {Array.from({length:25}).map((_,i) => <div key={i} style={{ width:12, height:12, background: Math.random()>0.5?'var(--ink)':'transparent', borderRadius:1 }}/>)}
                        </div>
                        <span style={{ fontSize:9, marginTop:4 }}>QR Code</span>
                      </div>
                    </div>
                  )}
                </>
              )}
            </div>

            {/* Notifications */}
            <div className="card card-pad">
              <div style={{ fontSize:14, fontWeight:600, color:'var(--ink)', marginBottom:14 }}>Customer Notifications</div>
              {[
                { id:'stage', label:'Stage change emails', sub:'Notify customer when deal moves to next stage', state:notifyOnStage, set:setNotifyOnStage },
                { id:'doc', label:'Document ready alerts', sub:'Notify when a quote or document is added', state:notifyOnDoc, set:setNotifyOnDoc },
              ].map(item => (
                <div key={item.id} style={{ display:'flex', alignItems:'center', justifyContent:'space-between', padding:'10px 0', borderBottom:'1px solid var(--border)' }}>
                  <div>
                    <div style={{ fontSize:13, fontWeight:500, color:'var(--ink)' }}>{item.label}</div>
                    <div style={{ fontSize:11.5, color:'var(--ink-3)', marginTop:2 }}>{item.sub}</div>
                  </div>
                  <button onClick={() => item.set(p=>!p)}
                    style={{ width:40, height:22, borderRadius:99, border:'none', cursor:'pointer', position:'relative', background: item.state ? 'var(--accent)' : 'var(--border)', transition:'background 0.2s', flexShrink:0 }}>
                    <span style={{ position:'absolute', top:2, left: item.state ? 20 : 2, width:18, height:18, borderRadius:99, background:'white', boxShadow:'0 1px 3px rgba(0,0,0,0.2)', transition:'left 0.2s' }} />
                  </button>
                </div>
              ))}
            </div>
          </div>

          {/* Stats sidebar */}
          <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
            <div className="card card-pad">
              <div style={{ fontSize:11, textTransform:'uppercase', letterSpacing:'0.08em', color:'var(--ink-3)', fontWeight:600, marginBottom:10 }}>Portal Activity</div>
              {[
                { label:'Last viewed', value:'2 hours ago' },
                { label:'Total visits', value:'14 times' },
                { label:'Docs downloaded', value:'2' },
                { label:'Messages sent', value:'6' },
              ].map(s => (
                <div key={s.label} style={{ display:'flex', justifyContent:'space-between', padding:'7px 0', borderBottom:'1px solid var(--border)', fontSize:13 }}>
                  <span style={{ color:'var(--ink-3)' }}>{s.label}</span>
                  <span style={{ fontWeight:600, color:'var(--ink)' }}>{s.value}</span>
                </div>
              ))}
            </div>
            <div className="card card-pad" style={{ background:'var(--accent)', border:'none', color:'white' }}>
              <div style={{ fontSize:12, opacity:0.8, marginBottom:8 }}>Current Stage</div>
              <div style={{ fontSize:17, fontWeight:700 }}>Quote Prepared</div>
              <div style={{ fontSize:12, opacity:0.75, marginTop:4 }}>Awaiting customer approval</div>
              <button style={{ marginTop:12, background:'rgba(255,255,255,0.2)', border:'1px solid rgba(255,255,255,0.3)', borderRadius:6, color:'white', padding:'6px 12px', fontSize:12, fontWeight:600, cursor:'pointer', display:'block', width:'100%' }} onClick={() => toast('Stage advanced · customer notified')}>
                Advance stage →
              </button>
            </div>
          </div>
        </div>
      )}

      {/* ── CUSTOMER VIEW PREVIEW ── */}
      {activeTab === 'preview' && (
        <div style={{ display:'grid', gridTemplateColumns:'1fr 320px', gap:16 }}>
          {/* Simulated customer portal */}
          <div style={{ background:'white', border:'2px solid var(--border)', borderRadius:'var(--r-xl)', overflow:'hidden', boxShadow:'var(--shadow-lg)' }}>
            {/* Portal header */}
            <div style={{ background:'linear-gradient(135deg, var(--accent) 0%, #0A4F3C 100%)', padding:'20px 24px', color:'white' }}>
              <div style={{ fontSize:11, opacity:0.7, letterSpacing:'0.08em', textTransform:'uppercase', marginBottom:4 }}>Your Kitchen Project</div>
              <div style={{ fontSize:18, fontWeight:700, letterSpacing:'-0.01em' }}>{selectedDeal?.customer || 'Customer'}</div>
              <div style={{ fontSize:12, opacity:0.75, marginTop:2 }}>Quote {selectedDeal?.id} · Updated today</div>
            </div>
            {/* Progress tracker */}
            <div style={{ padding:'20px 24px', borderBottom:'1px solid var(--border)' }}>
              <div style={{ fontSize:13, fontWeight:600, color:'var(--ink)', marginBottom:14 }}>Your Project Progress</div>
              <div style={{ display:'flex', gap:0 }}>
                {PORTAL_STAGES.map((s,i) => (
                  <div key={s.id} style={{ flex:1, display:'flex', flexDirection:'column', alignItems:'center', gap:4, position:'relative' }}>
                    {i > 0 && <div style={{ position:'absolute', top:14, left:'-50%', right:'50%', height:2, background: s.done ? 'var(--accent)' : 'var(--border)', zIndex:0 }} />}
                    <div style={{ width:28, height:28, borderRadius:99, background: s.done ? 'var(--accent)' : 'var(--surface-3)', border: s.done ? '2px solid var(--accent)' : '2px solid var(--border)', display:'flex', alignItems:'center', justifyContent:'center', fontSize:13, zIndex:1, position:'relative' }}>
                      {s.done ? '✓' : <span style={{ fontSize:11 }}>{s.icon}</span>}
                    </div>
                    <div style={{ fontSize:9.5, color: s.done ? 'var(--accent-ink)' : 'var(--ink-4)', textAlign:'center', fontWeight: s.done ? 600 : 400, lineHeight:1.3 }}>{s.label}</div>
                  </div>
                ))}
              </div>
            </div>
            {/* Documents */}
            <div style={{ padding:'16px 24px', borderBottom:'1px solid var(--border)' }}>
              <div style={{ fontSize:13, fontWeight:600, color:'var(--ink)', marginBottom:10 }}>Documents</div>
              {PORTAL_DOCS.map((doc,i) => (
                <div key={i} style={{ display:'flex', alignItems:'center', gap:10, padding:'8px 0', borderBottom:'1px solid var(--border)' }}>
                  <span style={{ fontSize:18 }}>{doc.type==='quote'?'📄':doc.type==='checklist'?'✅':'📋'}</span>
                  <div style={{ flex:1 }}>
                    <div style={{ fontSize:13, fontWeight:500, color:'var(--ink)' }}>{doc.name}</div>
                    <div style={{ fontSize:11, color:'var(--ink-3)' }}>{doc.date} {doc.signed && '· Signed ✓'}</div>
                  </div>
                  <button style={{ fontSize:12, padding:'4px 10px', borderRadius:5, border:'1px solid var(--border)', background:'var(--surface-2)', cursor:'pointer', color:'var(--ink-2)' }} onClick={() => toast(doc.signed ? 'Opening ' + doc.name : 'Sent ' + doc.name + ' for signature')}>
                    {doc.signed ? 'View' : 'Sign'}
                  </button>
                </div>
              ))}
            </div>
            {/* Messages */}
            <div style={{ padding:'16px 24px' }}>
              <div style={{ fontSize:13, fontWeight:600, color:'var(--ink)', marginBottom:12 }}>Messages</div>
              {PORTAL_MSGS.map((m,i) => (
                <div key={i} style={{ display:'flex', gap:8, marginBottom:12, flexDirection: m.from==='customer' ? 'row-reverse' : 'row' }}>
                  <div style={{ width:28, height:28, borderRadius:99, background: m.from==='designer'?'var(--accent)':'var(--surface-3)', display:'flex', alignItems:'center', justifyContent:'center', fontSize:10, fontWeight:700, color: m.from==='designer'?'white':'var(--ink-3)', flexShrink:0 }}>
                    {m.name.charAt(0)}
                  </div>
                  <div style={{ maxWidth:'80%' }}>
                    <div style={{ fontSize:11, color:'var(--ink-4)', marginBottom:3, textAlign: m.from==='customer'?'right':'left' }}>{m.name} · {m.time}</div>
                    <div style={{ background: m.from==='designer'?'var(--surface-2)':'var(--accent)', color: m.from==='designer'?'var(--ink-2)':'white', borderRadius: m.from==='designer'?'4px 10px 10px 10px':'10px 4px 10px 10px', padding:'9px 12px', fontSize:12.5, lineHeight:1.55 }}>
                      {m.text}
                    </div>
                  </div>
                </div>
              ))}
              <div style={{ display:'flex', gap:8, marginTop:8 }}>
                <input placeholder="Reply to your designer…" id="cp-reply" style={{ flex:1, border:'1px solid var(--border)', borderRadius:8, padding:'8px 12px', fontSize:13, outline:'none', background:'var(--surface-2)' }} />
                <button style={{ padding:'8px 14px', background:'var(--accent)', color:'white', border:'none', borderRadius:8, fontSize:13, fontWeight:600, cursor:'pointer' }} onClick={() => { const el = document.getElementById('cp-reply'); if (el && el.value.trim()) { toast('Reply sent to your designer'); el.value=''; } }}>Send</button>
              </div>
            </div>
          </div>

          {/* Preview label */}
          <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
            <div style={{ padding:'12px 14px', background:'var(--surface-2)', border:'1px solid var(--border)', borderRadius:8, fontSize:12, color:'var(--ink-3)', lineHeight:1.6 }}>
              <strong style={{ color:'var(--ink)' }}>This is what your customer sees</strong> when they open their portal link. It's live — any stage update or document you add appears instantly.
            </div>
            <div className="card card-pad">
              <div style={{ fontSize:13, fontWeight:600, color:'var(--ink)', marginBottom:10 }}>Share Portal</div>
              <button className="btn primary" style={{ width:'100%', justifyContent:'center', marginBottom:6 }} onClick={() => toast('Portal link emailed to ' + (selectedDeal?.customer || 'customer'))}>Email link to customer</button>
              <button className="btn" style={{ width:'100%', justifyContent:'center', marginBottom:6 }} onClick={() => toast('Portal link sent via SMS')}>Send via SMS</button>
              <button className="btn sm" style={{ width:'100%', justifyContent:'center', color:'var(--ink-3)' }} onClick={copyLink}>Copy link</button>
            </div>
          </div>
        </div>
      )}

      {/* ── ACTIVITY LOG ── */}
      {activeTab === 'activity' && (
        <div className="card">
          <div className="card-hd"><div className="card-title">Portal Activity Log</div><span style={{ fontSize:12, color:'var(--ink-3)' }}>All portal interactions for {selectedDeal?.customer || 'this deal'}</span></div>
          <div>
            {activityList.length === 0 && (
              <div style={{ padding:'18px 20px', fontSize:13, color:'var(--ink-3)' }}>No portal activity yet — it will appear here once the customer opens their link.</div>
            )}
            {activityList.map((ev, i) => (
              <div key={i} style={{ display:'flex', alignItems:'center', gap:12, padding:'11px 20px', borderBottom:'1px solid var(--border)' }}>
                <div style={{ width:32, height:32, borderRadius:99, background:ev.color, display:'flex', alignItems:'center', justifyContent:'center', fontSize:15, flexShrink:0 }}>{ev.icon}</div>
                <div style={{ flex:1, fontSize:13, color:'var(--ink-2)' }}>{ev.event}</div>
                <div style={{ fontSize:12, color:'var(--ink-4)', flexShrink:0 }}>{ev.time}</div>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

window.CustomerPortal = CustomerPortal;
