// Neal Communities — People directory + profiles, Weather-triggered Journeys

// ─── Weather icons ───────────────────────────────────────
const WX = {
  sunny: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" width="15" height="15"><circle cx="12" cy="12" r="4.5"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/></svg>,
  rainy: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" width="15" height="15"><path d="M16 13a4 4 0 0 0 .9-7.9A5.5 5.5 0 0 0 6.3 7 4 4 0 0 0 7 15h9"/><path d="M8 18.5l-.8 2M12 18.5l-.8 2M16 18.5l-.8 2"/></svg>,
  snow: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" width="15" height="15"><path d="M16 13a4 4 0 0 0 .9-7.9A5.5 5.5 0 0 0 6.3 7 4 4 0 0 0 7 15h9"/><path d="M9 19v.01M13 19v.01M9 21.5v.01M13 21.5v.01"/></svg>,
  cloudy: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" width="15" height="15"><path d="M17 18a4 4 0 0 0 .9-7.9A5.5 5.5 0 0 0 7.3 12 4 4 0 0 0 8 20h9z"/></svg>,
  cold: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" width="15" height="15"><path d="M12 2v20M5 5l14 14M19 5L5 19M2 12h20"/></svg>,
  pin: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" width="15" height="15"><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/><circle cx="12" cy="10" r="3"/></svg>,
};

function wxClass(tag) {
  return tag === 'sunny' ? 'wx-sun' : tag === 'rainy' ? 'wx-rain' : tag === 'snow' ? 'wx-snow' : 'wx-cloud';
}
WX.clock = <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" width="15" height="15"><circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 3"/></svg>;
WX.tag = <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" width="15" height="15"><path d="M20.6 13.4 13.4 20.6a2 2 0 0 1-2.8 0L3 13V3h10l7.6 7.6a2 2 0 0 1 0 2.8z"/><circle cx="7.5" cy="7.5" r="1.2" fill="currentColor" stroke="none"/></svg>;
function WxChip({ wx, sm }) {
  return (
    <span className={'wxchip ' + wxClass(wx.tag) + (sm ? ' sm' : '')}>
      {WX[wx.tag] || WX.cloudy}
      <span className="mono">{wx.temp}°</span>
      <span className="wxchip-cond">{wx.cond}</span>
    </span>
  );
}
function statusPillP(status) {
  const map = { 'Prospect': 'cold', 'Engaged': 'warm', 'Active buyer': 'won', 'Past buyer': '' };
  return <span className={'pill ' + (map[status] || '')}><span className="dot"/>{status}</span>;
}

// ═══ PEOPLE DIRECTORY ════════════════════════════════════
function NealPeople({ onSelectPerson, onOpenJourney }) {
  const d = window.NealData;
  const [seg, setSeg] = React.useState('all');
  const segs = [
    { id: 'all', label: 'All people' },
    { id: 'North', label: 'Up north' },
    { id: 'Florida', label: 'In Florida' },
    { id: 'Prospect', label: 'Prospects' },
    { id: 'Active buyer', label: 'Buyers' },
  ];
  const match = (p) => seg === 'all' ? true : (p.region === seg || p.status === seg);
  const list = d.people.filter(match);
  const northCount = d.people.filter(p => p.region === 'North' && p.status !== 'Active buyer').length;
  const inJourneys = d.people.filter(p => p.journeys.length).length;

  return (
    <div data-screen-label="07 People">
      <div className="page-head">
        <div>
          <div className="eyebrow accent" style={{marginBottom: 8}}>2,418 IN DATABASE · 486 PROMOTED TO BUYER LEADS · SHOWING {d.people.length} RECENT</div>
          <h1 className="page-title">Contacts</h1>
          <p className="page-sub">Everyone in your database — from first website visit to closed buyer. The assistant tracks what each contact does and, when they show real intent, promotes them to <strong>Buyer Leads</strong> for your sales team.</p>
        </div>
        <div className="page-actions">
          <button className="btn ghost">{NI.sparkle} Build an audience</button>
          <button className="btn">{NI.plus} Add person</button>
        </div>
      </div>

      {/* AI insight strip */}
      <div className="card insight-strip" style={{marginBottom: 20}}>
        <div className="ai-bug" style={{width: 32, height: 32, flexShrink: 0}}>{NI.sparkle}</div>
        <div style={{flex: 1, fontSize: 13, lineHeight: 1.55, color: 'var(--text)'}}>
          <strong>7 contacts hit a journey trigger today</strong> — 4 from this morning’s weather check (rain in Chicago), 2 price-drop alerts, and 1 tour follow-up. Sends are queued for 9:00 AM.
        </div>
        <button className="btn sm" onClick={() => onOpenJourney('rainy-north')}>View journey</button>
      </div>

      <div style={{display:'flex', gap: 6, marginBottom: 16}}>
        {segs.map(s => (
          <button key={s.id} onClick={() => setSeg(s.id)} className={'btn ' + (seg === s.id ? 'navy' : 'ghost') + ' sm'}>
            {s.label}
            <span className="mono" style={{opacity: 0.6, marginLeft: 4}}>{s.id === 'all' ? d.people.length : d.people.filter(p => p.region === s.id || p.status === s.id).length}</span>
          </button>
        ))}
      </div>

      <div className="card" style={{padding: 0}}>
        <table className="tbl">
          <thead><tr>
            <th style={{paddingLeft: 18}}>Person</th>
            <th>Last activity</th>
            <th>Status</th>
            <th>Interested in</th>
            <th>Source</th>
            <th>In journeys</th>
            <th style={{textAlign:'right', paddingRight: 18}}>Engagement</th>
          </tr></thead>
          <tbody>
            {list.map(p => (
              <tr key={p.id} onClick={() => onSelectPerson(p)}>
                <td style={{paddingLeft: 18}}>
                  <div className="av-row"><div className="av" style={{background: p.color}}>{p.initials}</div>
                    <div><div className="av-name">{p.name}</div><div className="av-meta">{p.id} · {p.city}, {p.state}</div></div>
                  </div>
                </td>
                <td style={{fontSize: 12, color:'var(--muted)', maxWidth: 190}}>{p.lastActivity}</td>
                <td>{statusPillP(p.status)}</td>
                <td style={{color:'var(--text)', fontSize: 12.5}}>{p.interest}</td>
                <td style={{fontSize: 12, color:'var(--muted)'}}>{p.source}</td>
                <td>
                  {p.journeys.length
                    ? <span className="mono" style={{fontSize: 12, color: 'var(--orange)', fontWeight: 600}}>{p.journeys.length}</span>
                    : <span style={{color: 'var(--subtle)', fontSize: 12}}>—</span>}
                </td>
                <td style={{paddingRight: 18}}>
                  <div style={{display:'flex', alignItems:'center', gap: 8, justifyContent:'flex-end'}}>
                    <div style={{width: 40, height: 4, background:'var(--bg-2)', borderRadius: 2, overflow:'hidden'}}>
                      <div style={{width: p.engagement + '%', height: '100%', background: 'linear-gradient(90deg, var(--navy), var(--orange))'}}/>
                    </div>
                    <span className="mono" style={{fontSize: 12}}>{p.engagement}</span>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ═══ PERSON PROFILE ══════════════════════════════════════
function NealPerson({ person, onBack, onOpenJourney, onOpenLead }) {
  const d = window.NealData;
  const p = person;
  const [tab, setTab] = React.useState('journeys');
  const enrolled = d.journeys.filter(j => p.journeys.includes(j.id));
  const isNorth = p.region === 'North';
  const linkedLead = p.leadId && d.leads.find(l => l.id === p.leadId);

  const emailLog = [
    { j: 'rainy-north', subj: 'It’s 41° and raining in Chicago. It’s 79° and sunny in Sarasota.', time: '2h ago', state: 'Opened', dot: 'good' },
    { j: 'rainy-north', subj: 'Your future backyard doesn’t need a snow shovel', time: '6d ago', state: 'Clicked', dot: 'orange' },
    { j: 'snowbird', subj: 'Skip the shovel this winter — your Florida home is waiting', time: '2w ago', state: 'Opened', dot: 'good' },
  ];

  return (
    <div data-screen-label="08 Person">
      <div className="page-head">
        <div>
          <div style={{display:'flex', alignItems:'center', gap: 10, marginBottom: 8}}>
            <span className="eyebrow" style={{cursor:'pointer'}} onClick={onBack}>← CONTACTS</span>
            <span style={{color:'var(--subtle)'}}>/</span>
            <span className="eyebrow accent">{p.id}</span>
          </div>
          <div style={{display:'flex', alignItems:'center', gap: 14}}>
            <h1 className="page-title" style={{margin: 0}}>{p.name}</h1>
            {statusPillP(p.status)}
          </div>
          <p className="page-sub" style={{marginTop: 6}}>{p.city}, {p.state} · interested in {p.interest} · {p.timeline}</p>
        </div>
        <div className="page-actions">
          <button className="btn ghost sm">Call</button>
          <button className="btn ghost sm">Email</button>
          {linkedLead
            ? <button className="btn navy sm" onClick={() => onOpenLead && onOpenLead(linkedLead)}>Open buyer lead {NI.chevron}</button>
            : <button className="btn navy sm">{NI.plus} Promote to buyer lead</button>}
          <button className="btn">{NI.sparkle} Draft outreach</button>
        </div>
      </div>

      {/* Weather contrast hero — the whole pitch in one strip */}
      {isNorth && (
        <div className="wx-contrast" style={{marginBottom: 18}}>
          <div className={'wx-side ' + wxClass(p.wx.tag)}>
            <div className="wx-side-icon">{WX[p.wx.tag]}</div>
            <div>
              <div className="wx-side-label">Right now in {p.city}</div>
              <div className="wx-side-temp">{p.wx.temp}°<span>{p.wx.cond}</span></div>
            </div>
          </div>
          <div className="wx-arrow">{NI.sparkle}<span>relocation pull</span></div>
          <div className="wx-side wx-sun">
            <div className="wx-side-icon">{WX.sunny}</div>
            <div>
              <div className="wx-side-label">Right now in Sarasota, FL</div>
              <div className="wx-side-temp">{d.weather.florida.temp}°<span>Sunny · 11 hrs of sun</span></div>
            </div>
          </div>
          <div className="wx-cta">
            <div style={{fontSize: 12.5, color:'var(--text)', lineHeight: 1.5}}>
              That’s a <strong>{d.weather.florida.temp - p.wx.temp}° swing</strong>. {p.name.split(' ')[0]} has opened 2 of the last 3 Florida emails — intent is climbing.
            </div>
          </div>
        </div>
      )}

      <div className="card insight-strip" style={{marginBottom: 18, background: 'linear-gradient(90deg, var(--orange-soft), transparent 70%)', borderColor: 'var(--orange-line)'}}>
        <div className="ai-bug" style={{width: 32, height: 32, flexShrink: 0}}>{NI.sparkle}</div>
        <div style={{flex: 1, fontSize: 13, lineHeight: 1.55, color:'var(--text)'}}>
          {linkedLead
            ? <><strong>Promoted to buyer lead {p.leadId}.</strong> Your sales team works them from the pipeline — this contact record keeps the full marketing history: every email, form, and page view.</>
            : <><strong>Intent score {p.engagement} and climbing.</strong> {p.lastActivity}. {p.engagement >= 70 ? 'One more engaged touch and the assistant will recommend promoting them to a buyer lead.' : 'The assistant will flag them for promotion when intent crosses 85.'}</>}
        </div>
        {linkedLead
          ? <button className="btn sm" onClick={() => onOpenLead && onOpenLead(linkedLead)}>View pipeline record</button>
          : <button className="btn sm">{NI.plus} Add to journey</button>}
      </div>

      <div className="lead-layout">
        <div className="card profile-card">
          <div className="profile-av" style={{background: p.color}}>{p.initials}</div>
          <div className="profile-name">{p.name}</div>
          <div className="profile-role">{p.city}, {p.state}</div>
          <div style={{display:'flex', gap: 6, marginTop: 12, flexWrap:'wrap'}}>
            {statusPillP(p.status)}
            <span className={'pill ' + (p.climate === 'High' ? 'orange' : 'warm')}>{p.climate} climate pull</span>
          </div>
          <div className="profile-grid">
            <div className="profile-row"><div className="lbl">EMAIL</div><div className="val">{p.email}</div></div>
            <div className="profile-row"><div className="lbl">PHONE</div><div className="val mono">{p.phone}</div></div>
            <div className="profile-row"><div className="lbl">LOCATION</div><div className="val">{p.city}, {p.state}</div></div>
            <div className="profile-row"><div className="lbl">WEATHER</div><div className="val"><WxChip wx={p.wx} sm/></div></div>
            <div className="profile-row"><div className="lbl">TIMELINE</div><div className="val">{p.timeline}</div></div>
            <div className="profile-row"><div className="lbl">SOURCE</div><div className="val">{p.source}</div></div>
            <div className="profile-row"><div className="lbl">COUNSELOR</div><div className="val"><div className="av-row"><div className="av" style={{background:'var(--navy)', width: 22, height: 22, fontSize: 9}}>JC</div>Jasmine Carter</div></div></div>
          </div>
          <hr className="div"/>
          <div className="eyebrow" style={{marginBottom: 12}}>WHAT THEY WANT</div>
          <div style={{display:'flex', flexWrap:'wrap', gap: 6}}>
            {p.wants.map(w => <span className="pill" key={w}>{w}</span>)}
          </div>
        </div>

        <div>
          <div className="card">
            <div className="tabs" style={{padding: '0 18px'}}>
              {[
                { id: 'journeys', label: 'Journeys', count: enrolled.length },
                { id: 'emails', label: 'Emails', count: emailLog.length },
                { id: 'activity', label: 'Activity' },
              ].map(t => (
                <div key={t.id} className={'tab ' + (tab === t.id ? 'active' : '')} onClick={() => setTab(t.id)}>
                  {t.label}{t.count !== undefined && <span className="mono" style={{marginLeft: 6, color:'var(--muted)', fontSize: 11}}>{t.count}</span>}
                </div>
              ))}
            </div>
            <div className="card-body" style={{padding: 22}}>
              {tab === 'journeys' && (
                <div>
                  <div className="eyebrow" style={{marginBottom: 14}}>{NI.sparkle} ENROLLED IN {enrolled.length} {enrolled.length === 1 ? 'JOURNEY' : 'JOURNEYS'}</div>
                  {enrolled.length === 0 && <div style={{color:'var(--muted)', fontSize: 13}}>Not in any journey yet. {isNorth && 'This contact qualifies for the weather-triggered journeys.'}</div>}
                  <div style={{display:'flex', flexDirection:'column', gap: 12}}>
                    {enrolled.map(j => (
                      <div key={j.id} className="enroll-row" onClick={() => onOpenJourney(j.id)}>
                        <div className={'recipe-ic ' + wxClass(j.trigger.icon)}>{WX[j.trigger.icon] || WX.pin}</div>
                        <div style={{flex: 1}}>
                          <div style={{display:'flex', alignItems:'center', gap: 8}}>
                            <span style={{fontWeight: 700, color:'var(--ink)', fontSize: 14}}>{j.name}</span>
                            <span className={'pill ' + (j.status === 'active' ? 'won' : '')} style={{fontSize: 10}}><span className="dot"/>{j.status}</span>
                          </div>
                          <div style={{fontSize: 12, color:'var(--muted)', marginTop: 3}}>{j.trigger.summary}</div>
                        </div>
                        <div style={{textAlign:'right'}}>
                          <div className="mono" style={{fontSize: 13, color:'var(--orange)', fontWeight: 600}}>{j.metrics.openRate}%</div>
                          <div className="eyebrow" style={{fontSize: 9}}>open rate</div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}
              {tab === 'emails' && (
                <div>
                  <div className="eyebrow" style={{marginBottom: 14}}>EMAILS SENT BY JOURNEYS</div>
                  <div style={{display:'flex', flexDirection:'column', gap: 0}}>
                    {emailLog.map((e, i) => (
                      <div key={i} style={{display:'flex', alignItems:'center', gap: 12, padding: '12px 0', borderBottom: i < emailLog.length-1 ? '1px solid var(--border)' : 0}}>
                        <span className={'pill ' + (e.dot === 'good' ? 'won' : 'orange')} style={{fontSize: 10, flexShrink: 0}}><span className="dot"/>{e.state}</span>
                        <div style={{flex: 1, minWidth: 0}}>
                          <div style={{fontSize: 13, color:'var(--ink)', fontWeight: 600, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap'}}>{e.subj}</div>
                          <div style={{fontSize: 11.5, color:'var(--muted)', marginTop: 2}}>via {d.journeys.find(j => j.id === e.j)?.name}</div>
                        </div>
                        <span className="mono" style={{fontSize: 11, color:'var(--subtle)', flexShrink: 0}}>{e.time}</span>
                      </div>
                    ))}
                  </div>
                </div>
              )}
              {tab === 'activity' && (
                <NealWebActivity onOpenJourney={onOpenJourney}/>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { WX, WxChip, statusPillP, wxClass, NealPeople, NealPerson });
