// Neal Communities — Dashboard + Homes + Lead detail + Communities + Pipeline

function NSparkline({ data, color = 'var(--navy)' }) {
  const w = 200, h = 36;
  const max = Math.max(...data), min = Math.min(...data);
  const pts = data.map((v, i) => {
    const x = (i / (data.length - 1)) * w;
    const y = h - ((v - min) / (max - min || 1)) * (h - 4) - 2;
    return `${x},${y}`;
  }).join(' ');
  return (
    <svg className="sparkline" viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none">
      <polyline points={`0,${h} ${pts} ${w},${h}`} fill={color} opacity="0.10"/>
      <polyline points={pts} fill="none" stroke={color} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  );
}

function NStat({ label, value, delta, dir, sub, spark, color }) {
  return (
    <div className="stat">
      <div className="stat-label">{label}</div>
      <div className="stat-value">{value}</div>
      <div className="stat-foot">
        <span className={'delta ' + dir}>{dir === 'up' ? NI.up : NI.down}{delta}</span>
        <span>{sub}</span>
      </div>
      {spark && <NSparkline data={spark} color={color}/>}
    </div>
  );
}

// ─── Status ribbon helper ─────────────────────────────────
function statusPill(status) {
  if (status === 'Move-in Ready') return <span className="pill won"><span className="dot"/>Move-in Ready</span>;
  if (status === 'In Progress') return <span className="pill cold"><span className="dot"/>In Progress</span>;
  if (status === 'Pre-Construction') return <span className="pill warm"><span className="dot"/>Pre-Construction</span>;
  return <span className="pill orange"><span className="dot"/>Summer Event</span>;
}

// ═══ DASHBOARD ═══════════════════════════════════════════
function NealDashboard({ onSelectLead, onSelectCommunity }) {
  const d = window.NealData;
  return (
    <div data-screen-label="01 Dashboard">
      <div className="page-head">
        <div>
          <div className="eyebrow accent" style={{marginBottom: 8}}>TUESDAY · 9 JUNE</div>
          <h1 className="page-title">Good morning, Jasmine.</h1>
          <p className="page-sub">12 new leads came in overnight. The Neal Assistant has already matched homes and drafted tour invites for your 3 hottest buyers.</p>
        </div>
        <div className="page-actions">
          <button className="btn ghost">This month {NI.chevronDown}</button>
          <button className="btn">{NI.plus} New lead</button>
        </div>
      </div>

      <div className="grid cols-4" style={{marginBottom: 22}}>
        <NStat label="ACTIVE BUYERS" value={d.stats.leads.value} delta={d.stats.leads.delta} dir={d.stats.leads.dir} sub={d.stats.leads.sub} spark={[20,26,22,30,34,32,40,44,42,48,52,49,55,60]} color="var(--navy)"/>
        <NStat label="AVAILABLE HOMES" value={d.stats.homes.value} delta={d.stats.homes.delta} dir={d.stats.homes.dir} sub={d.stats.homes.sub} spark={[88,90,86,92,95,93,98,97,99,101,100,102,101,103]} color="var(--orange)"/>
        <NStat label="PIPELINE VALUE" value={d.stats.volume.value} delta={d.stats.volume.delta} dir={d.stats.volume.dir} sub={d.stats.volume.sub} spark={[28,30,33,32,35,37,36,38,39,38,40,41,41,42]} color="var(--good)"/>
        <NStat label="SPEED TO CONTRACT" value={d.stats.speed.value} delta={d.stats.speed.delta} dir={d.stats.speed.dir} sub={d.stats.speed.sub} spark={[55,52,53,48,49,45,44,43,41,40,39,40,39,38]} color="var(--info)"/>
      </div>

      <div className="grid cols-2" style={{marginBottom: 22}}>
        <div className="card">
          <div className="card-head">
            <div>
              <div className="card-title">Buyer journey funnel</div>
              <div style={{fontSize: 11.5, color: 'var(--muted)', marginTop: 2}}>All communities · last 90 days</div>
            </div>
            <button className="btn ghost sm">Export</button>
          </div>
          <div className="card-body">
            {d.funnel.map((row, i) => (
              <div className="funnel-row" key={row.stage}>
                <div className="funnel-stage">{row.stage}</div>
                <div className="funnel-bar"><div className="funnel-fill" style={{width: row.pct + '%', background: i === d.funnel.length-1 ? 'linear-gradient(90deg, var(--orange), var(--orange-hi))' : undefined}}/></div>
                <div className="funnel-cnt">{row.count}</div>
                <div className="funnel-pct">{row.pct}%</div>
              </div>
            ))}
          </div>
        </div>

        <div className="card">
          <div className="card-head">
            <div>
              <div className="card-title">Priority buyers</div>
              <div style={{fontSize: 11.5, color: 'var(--muted)', marginTop: 2}}>Ranked by AI intent · refreshed 6m ago</div>
            </div>
            <span className="pill orange">{NI.sparkle} AI</span>
          </div>
          <div className="card-body" style={{padding: 0}}>
            {d.leads.filter(l => l.score >= 68).slice(0, 5).map(l => (
              <div key={l.id} onClick={() => onSelectLead(l)} style={{display:'grid', gridTemplateColumns:'1fr auto 64px', alignItems:'center', gap: 12, padding: '12px 18px', borderBottom: '1px solid var(--border)', cursor:'pointer'}}>
                <div className="av-row">
                  <div className="av" style={{background: l.color}}>{l.initials}</div>
                  <div>
                    <div className="av-name">{l.name}</div>
                    <div className="av-meta">{l.interest}</div>
                  </div>
                </div>
                <span className={'pill ' + (l.heat === 'won' ? 'won' : l.heat)} style={{fontSize: 10.5}}><span className="dot"/>{l.stage}</span>
                <span className="pill orange" style={{fontSize: 10.5, justifySelf: 'end'}}>{l.score}</span>
              </div>
            ))}
            <div style={{padding: 12, textAlign: 'center'}}><button className="btn ghost sm">View all 486 buyers</button></div>
          </div>
        </div>
      </div>

      <div className="grid" style={{gridTemplateColumns: '1.4fr 1fr', gap: 16}}>
        <div className="card">
          <div className="card-head"><div className="card-title">Activity stream</div>
            <div style={{display:'flex', gap: 6}}>
              <span className="pill" style={{fontSize: 10.5}}><span className="dot" style={{background:'var(--navy)'}}/>All</span>
              <span className="pill" style={{fontSize: 10.5}}>Tours</span>
            </div>
          </div>
          <div className="card-body">
            <div className="timeline">
              {d.activity.map((ev, i) => (
                <div key={i} className={'event ' + (ev.type === 'ai' ? 'ai' : ev.type === 'orange' ? 'orange' : '')}>
                  <div className="marker"/>
                  <div className="event-head"><span className="event-actor">{ev.actor}</span><span className="event-action">{ev.action}</span><span className="event-time">{ev.time}</span></div>
                  <div className="event-body">{ev.body}</div>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div className="card">
          <div className="card-head"><div className="card-title">Community performance</div><button className="btn ghost sm">All</button></div>
          <div className="card-body" style={{padding: 0}}>
            {d.communities.map((c, i) => (
              <div key={c.name} onClick={() => onSelectCommunity && onSelectCommunity(c)} style={{padding: '14px 18px', borderBottom: i < d.communities.length-1 ? '1px solid var(--border)' : 0, display:'flex', alignItems:'center', justifyContent:'space-between', cursor:'pointer'}}>
                <div>
                  <div style={{fontSize: 14, fontWeight: 700, color: 'var(--ink)', fontFamily: 'var(--serif)'}}>{c.name}</div>
                  <div style={{fontSize: 11.5, color: 'var(--muted)', marginTop: 2}}>{c.city} · {c.homes} homes · from {c.from}</div>
                </div>
                <div style={{textAlign: 'right'}}>
                  <div className="mono" style={{fontSize: 13, color: 'var(--orange)', fontWeight: 600}}>{c.leads}</div>
                  <div style={{fontSize: 10, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.1em', fontWeight: 600}}>leads</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// ═══ HOMES (signature screen, matches neal site) ═════════
function NealHomes({ onSelectLead, onSelectHome }) {
  const d = window.NealData;
  const filters = ['Price', 'Sq Ft', 'Bedrooms', 'Bathrooms', 'Garages', 'Story', 'Community', 'Location', 'Plan', 'Style'];
  return (
    <div data-screen-label="05 Homes">
      <div className="page-head">
        <div>
          <div className="eyebrow accent" style={{marginBottom: 8}}>103 AVAILABLE · 4 COMMUNITIES · $41.8M VALUE</div>
          <h1 className="page-title">Browse Homes</h1>
          <p className="page-sub">Every home syncs live to nealcommunities.com. The Neal Assistant flags which homes best fit each active buyer.</p>
        </div>
        <div className="page-actions">
          <button className="btn ghost">{NI.sparkle} Match to a buyer</button>
          <button className="btn">{NI.plus} Add home</button>
        </div>
      </div>

      <div className="filterbar">
        {filters.map(f => (
          <div className="filter" key={f}>{f} {NI.chevronDown}</div>
        ))}
        <div className="filter reset">Reset</div>
      </div>

      <div className="home-grid">
        {d.homes.map(h => (
          <div className="home-card" key={h.name + h.city} onClick={() => onSelectHome && onSelectHome(h)}>
            <div className="home-photo" style={h.photo ? {backgroundImage: 'url("' + h.photo + '")', backgroundSize: 'cover', backgroundPosition: 'center'} : undefined}>
              {!h.photo && <div className="sky"/>}
              <div className={'ribbon' + (h.status === 'Summer' ? ' summer' : '')}>
                {h.status === 'Summer' ? 'Stay in Summer' : h.status}
              </div>
              {!h.photo && <span style={{position: 'relative', zIndex: 1, marginTop: 30}}>Home Rendering</span>}
            </div>
            <div className="home-body">
              <div className="home-name">{h.name.toUpperCase()}</div>
              <div className="home-type">{h.type}</div>
              <div className="home-comm">{h.community}</div>
              <div className="home-loc">{NI.pin} {h.city}</div>
              <div className="home-price">PRICED AT <strong>{h.price}</strong></div>
              <div className="home-specs">{h.bed} BED · {h.bath} BATH · {h.garage} GARAGE · {h.story} STORY</div>
              <div className="home-sqft">{h.sqft} SQ FT</div>
            </div>
            <div className="home-ai">
              {NI.sparkle}
              <span><strong>{h.match}% match</strong> for David &amp; Karen · {h.leads} active leads · {h.views} views</span>
            </div>
            <div className="home-actions">
              <button className="dl" onClick={(e) => e.stopPropagation()}>Download</button>
              <button className="sh" onClick={(e) => e.stopPropagation()}>Share</button>
              <button className="vw">View</button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ═══ LEADS LIST ══════════════════════════════════════════
function NealLeads({ onSelectLead }) {
  const d = window.NealData;
  const [filter, setFilter] = React.useState('all');
  const filters = ['all', 'hot', 'warm', 'cold', 'won'];
  return (
    <div data-screen-label="03 Leads">
      <div className="page-head">
        <div>
          <div className="eyebrow accent" style={{marginBottom: 8}}>486 ACTIVE · 12 NEW TODAY</div>
          <h1 className="page-title">Buyer Leads</h1>
          <p className="page-sub">Sales-qualified buyers your team is actively working. Contacts graduate here when they show real intent — the assistant scores them and matches homes within minutes.</p>
        </div>
        <div className="page-actions">
          <button className="btn ghost">Import</button>
          <button className="btn">{NI.plus} New lead</button>
        </div>
      </div>

      <div style={{display:'flex', gap: 6, marginBottom: 16}}>
        {filters.map(f => (
          <button key={f} onClick={() => setFilter(f)} className={'btn ' + (filter === f ? 'navy' : 'ghost') + ' sm'} style={{textTransform: 'capitalize'}}>
            {f === 'all' ? 'All buyers' : f}
            <span className="mono" style={{opacity: 0.6, marginLeft: 4}}>{f === 'all' ? d.leads.length : d.leads.filter(l => l.heat === f).length}</span>
          </button>
        ))}
      </div>

      <div className="card" style={{padding: 0}}>
        <table className="tbl">
          <thead><tr>
            <th style={{paddingLeft: 18}}>Buyer</th>
            <th>Interested in</th>
            <th>Budget</th>
            <th>Timeline</th>
            <th>Stage</th>
            <th>AI score</th>
            <th>Pre-approved</th>
            <th style={{textAlign:'right', paddingRight: 18}}>Last touch</th>
          </tr></thead>
          <tbody>
            {(filter === 'all' ? d.leads : d.leads.filter(l => l.heat === filter)).map(l => (
              <tr key={l.id} onClick={() => onSelectLead(l)}>
                <td style={{paddingLeft: 18}}>
                  <div className="av-row"><div className="av" style={{background: l.color}}>{l.initials}</div>
                    <div><div className="av-name">{l.name}</div><div className="av-meta">{l.id} · {l.city}</div></div>
                  </div>
                </td>
                <td>{l.interest}</td>
                <td className="mono" style={{color: 'var(--ink)'}}>{l.budget}</td>
                <td style={{color: 'var(--muted)', fontSize: 12.5}}>{l.timeline}</td>
                <td><span className={'pill ' + (l.heat === 'won' ? 'won' : l.heat)}><span className="dot"/>{l.stage}</span></td>
                <td>
                  <div style={{display:'flex', alignItems:'center', gap: 8}}>
                    <div style={{width: 40, height: 4, background:'var(--bg-2)', borderRadius: 2, overflow:'hidden'}}>
                      <div style={{width: l.score + '%', height: '100%', background: 'linear-gradient(90deg, var(--navy), var(--orange))'}}/>
                    </div>
                    <span className="mono" style={{fontSize: 12}}>{l.score}</span>
                  </div>
                </td>
                <td>{l.preApproved ? <span className="pill won" style={{fontSize: 10.5}}><span className="dot"/>Yes</span> : <span className="pill" style={{fontSize: 10.5}}>Not yet</span>}</td>
                <td className="mono" style={{textAlign:'right', paddingRight: 18, fontSize: 11.5, color:'var(--muted)'}}>{l.lastTouch}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ═══ LEAD DETAIL (hero — AI home matching) ═══════════════
// ═══ WEB ACTIVITY FEED — page views, forms, emails, journeys ═
const ACT_ICONS = {
  page: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" width="14" height="14"><circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18"/></svg>,
  form: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" width="14" height="14"><rect x="5" y="3" width="14" height="18" rx="2"/><path d="M9 8h6M9 12h6M9 16h3"/></svg>,
  email: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" width="14" height="14"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="m3 7 9 6 9-6"/></svg>,
  journey: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" width="14" height="14"><circle cx="5" cy="6" r="2"/><circle cx="19" cy="6" r="2"/><circle cx="12" cy="18" r="2"/><path d="M7 6h6a4 4 0 0 1 4 4v.5M12 8v8"/></svg>,
};
const ACT_FILTERS = [
  { id: 'all', label: 'All' },
  { id: 'page', label: 'Website' },
  { id: 'form', label: 'Forms' },
  { id: 'email', label: 'Emails' },
  { id: 'journey', label: 'Journeys' },
];

function NealWebActivity({ onOpenJourney }) {
  const d = window.NealData;
  const [f, setF] = React.useState('all');
  const list = d.webActivity.filter(ev => f === 'all' || ev.group === f);
  const count = (id) => id === 'all' ? d.webActivity.length : d.webActivity.filter(e => e.group === id).length;
  return (
    <div>
      <div className="act-stats">
        {d.webStats.map(s => (
          <div className="act-stat" key={s.l}><div className="act-stat-v">{s.v}</div><div className="act-stat-l">{s.l}</div></div>
        ))}
      </div>
      <div style={{display:'flex', gap: 6, margin: '16px 0 14px', flexWrap:'wrap'}}>
        {ACT_FILTERS.map(x => (
          <button key={x.id} className={'btn ' + (f === x.id ? 'navy' : 'ghost') + ' sm'} onClick={() => setF(x.id)}>
            {x.label}<span className="mono" style={{opacity: 0.6, marginLeft: 4}}>{count(x.id)}</span>
          </button>
        ))}
      </div>
      <div className="act-feed">
        {list.map((ev, i) => {
          const j = ev.journey && d.journeys.find(x => x.id === ev.journey);
          return (
            <div className="act-row" key={i}>
              <div className={'act-ic ' + ev.group}>{ACT_ICONS[ev.group]}</div>
              <div className="act-main">
                <div className="act-head">
                  <span className="act-kind">{ev.kind}</span>
                  <span className="act-time mono">{ev.time}</span>
                </div>
                <div className="act-title">{ev.title}</div>
                <div className="act-body">{ev.body}</div>
                {j && (
                  <button className="act-journey" onClick={() => onOpenJourney && onOpenJourney(j.id)}>
                    {NI.sparkle} {j.name} {NI.chevron}
                  </button>
                )}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function NealLeadDetail({ lead, onBack, onOpenJourney }) {
  const [tab, setTab] = React.useState('activity');
  const d = window.NealData;
  const tabs = [
    { id: 'activity', label: 'Activity' },
    { id: 'matches', label: 'Home matches', count: 3 },
    { id: 'tours', label: 'Tours', count: 2 },
    { id: 'docs', label: 'Documents', count: 5 },
  ];
  const matches = d.homes.slice(0, 3);

  return (
    <div data-screen-label="04 Lead Detail">
      <div className="page-head">
        <div>
          <div style={{display:'flex', alignItems:'center', gap: 10, marginBottom: 8}}>
            <span className="eyebrow" style={{cursor:'pointer'}} onClick={onBack}>← LEADS</span>
            <span style={{color:'var(--subtle)'}}>/</span>
            <span className="eyebrow accent">{lead.id}</span>
          </div>
          <div style={{display:'flex', alignItems:'center', gap: 14}}>
            <h1 className="page-title" style={{margin: 0}}>{lead.name}</h1>
            <span className={'pill ' + (lead.heat === 'won' ? 'won' : lead.heat)}><span className="dot"/>{lead.stage} · {lead.score}</span>
          </div>
          <p className="page-sub" style={{marginTop: 6}}>{lead.city} · interested in {lead.interest} · {lead.timeline}</p>
        </div>
        <div className="page-actions">
          <button className="btn ghost sm">Call</button>
          <button className="btn ghost sm">Email</button>
          <button className="btn navy sm">Schedule tour</button>
          <button className="btn">{NI.sparkle} Match homes</button>
        </div>
      </div>

      <div className="card" style={{padding: 14, marginBottom: 18, background: 'linear-gradient(90deg, var(--orange-soft), transparent 70%)', borderColor: 'var(--orange-line)'}}>
        <div style={{display:'flex', alignItems:'center', gap: 14}}>
          <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>Strong buyer.</strong> Pre-approved at $320k, opened the Avery floor plan 4× and downloaded the Palm Grove site map. The Avery is a <strong>96% match</strong> — book the model tour this weekend while intent is high.
          </div>
          <button className="btn sm">Draft tour invite</button>
        </div>
      </div>

      <div className="lead-layout">
        <div className="card profile-card">
          <div className="profile-av" style={{background: lead.color}}>{lead.initials}</div>
          <div className="profile-name">{lead.name}</div>
          <div className="profile-role">{lead.city}</div>
          <div style={{display:'flex', gap: 6, marginTop: 12}}>
            {lead.preApproved
              ? <span className="pill won"><span className="dot"/>Pre-approved</span>
              : <span className="pill warm"><span className="dot"/>Needs lender</span>}
          </div>
          <div className="profile-grid">
            <div className="profile-row"><div className="lbl">EMAIL</div><div className="val">{lead.email}</div></div>
            <div className="profile-row"><div className="lbl">PHONE</div><div className="val mono">{lead.phone}</div></div>
            <div className="profile-row"><div className="lbl">BUDGET</div><div className="val mono">{lead.budget}</div></div>
            <div className="profile-row"><div className="lbl">TIMELINE</div><div className="val">{lead.timeline}</div></div>
            <div className="profile-row"><div className="lbl">SOURCE</div><div className="val">{lead.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}}>WANTS</div>
          <div style={{display:'flex', flexWrap:'wrap', gap: 6}}>
            <span className="pill">3+ bed</span><span className="pill">2-car ideal</span><span className="pill">Lakewood Ranch</span><span className="pill">Preserve lot</span><span className="pill">Move in &lt; 90d</span>
          </div>
        </div>

        <div>
          <div className="card">
            <div className="tabs" style={{padding: '0 18px'}}>
              {tabs.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 === 'matches' ? (
                <div>
                  <div className="eyebrow" style={{marginBottom: 14}}>{NI.sparkle} AI-RANKED HOME MATCHES</div>
                  <div style={{display:'flex', flexDirection:'column', gap: 12}}>
                    {matches.map((h, i) => (
                      <div key={h.name} style={{display:'flex', gap: 16, alignItems:'center', padding: 14, border: '1px solid var(--border)', borderRadius: 10, background: i === 0 ? 'var(--orange-soft)' : 'var(--surface)', borderColor: i === 0 ? 'var(--orange-line)' : 'var(--border)'}}>
                        <div style={{width: 92, height: 64, borderRadius: 8, background: 'linear-gradient(170deg, #cfdceb, #9bb4cf)', flexShrink: 0}}/>
                        <div style={{flex: 1}}>
                          <div style={{display:'flex', alignItems:'center', gap: 10}}>
                            <span style={{fontFamily:'var(--serif)', fontSize: 20, fontWeight: 600, color:'var(--ink)'}}>{h.name}</span>
                            <span className="home-type" style={{margin: 0}}>{h.type}</span>
                          </div>
                          <div style={{fontSize: 12.5, color:'var(--muted)', marginTop: 3}}>{h.community} · {h.city}</div>
                          <div style={{fontSize: 12, color:'var(--text)', marginTop: 6, fontWeight: 600}}>{h.price} · {h.bed}/{h.bath} · {h.sqft} sq ft</div>
                        </div>
                        <div style={{textAlign:'center'}}>
                          <div style={{fontFamily:'var(--serif)', fontSize: 30, fontWeight: 600, color: 'var(--orange)'}}>{h.match}%</div>
                          <div className="eyebrow" style={{fontSize: 9}}>MATCH</div>
                          <button className="btn sm" style={{marginTop: 8}}>Send</button>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              ) : (
                <>
                  <div style={{border: '1px solid var(--border)', borderRadius: 10, padding: 12, background: 'var(--bg-2)', marginBottom: 20}}>
                    <div style={{display:'flex', gap: 6, marginBottom: 10}}>
                      <button className="btn navy sm">Note</button>
                      <button className="btn ghost sm">Email</button>
                      <button className="btn ghost sm">Log tour</button>
                      <div style={{marginLeft:'auto'}}><button className="btn ghost sm">{NI.sparkle} Generate</button></div>
                    </div>
                    <div style={{minHeight: 50, color:'var(--subtle)', fontSize: 13, padding: '4px'}}>Add a note or ask the assistant to draft a follow-up for {lead.name.split(' ')[0]}…</div>
                  </div>
                  <NealWebActivity onOpenJourney={onOpenJourney}/>
                </>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ═══ COMMUNITIES ═════════════════════════════════════════
function NealCommunities({ onSelectCommunity }) {
  const d = window.NealData;
  return (
    <div data-screen-label="06 Communities">
      <div className="page-head">
        <div>
          <div className="eyebrow accent" style={{marginBottom: 8}}>4 ACTIVE · 359 LEADS · $41.8M PIPELINE</div>
          <h1 className="page-title">Communities</h1>
          <p className="page-sub">Performance across every Neal community. Track inventory, lead flow, and sell-through in one place.</p>
        </div>
        <div className="page-actions"><button className="btn">{NI.plus} New community</button></div>
      </div>

      <div className="grid cols-2">
        {d.communities.map(c => (
          <div className="card" key={c.name} onClick={() => onSelectCommunity && onSelectCommunity(c)} style={{overflow:'hidden', cursor:'pointer'}}>
            <div style={{height: 210, position: 'relative', display:'grid', placeItems:'center', backgroundImage: c.photo ? 'url("' + c.photo + '")' : 'linear-gradient(170deg, #bcd4ec, #9bb4cf 60%, #7d9bbb)', backgroundSize: 'cover', backgroundPosition: 'center'}}>
              <div style={{position:'absolute', inset: 0, background:'linear-gradient(180deg, rgba(13,41,68,0.18), transparent 45%)'}}></div>
              {!c.photo && <span style={{position:'relative', color:'#5c789a', fontSize: 10.5, letterSpacing:'0.16em', textTransform:'uppercase', fontWeight: 600}}>Community Aerial</span>}
              <div style={{position:'absolute', top: 14, left: 14}}>{c.type === 'Single Family' ? <span className="pill won"><span className="dot"/>{c.type}</span> : <span className="pill cold"><span className="dot"/>{c.type}</span>}</div>
            </div>
            <div className="card-body">
              <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start'}}>
                <div style={{minWidth: 0}}>
                  <div style={{fontFamily:'var(--serif)', fontSize: 26, fontWeight: 600, color:'var(--ink)', lineHeight: 1.1}}>{c.name}</div>
                  <div className="home-loc" style={{justifyContent:'flex-start', marginTop: 6}}>{NI.pin} {c.city}</div>
                </div>
                <div style={{textAlign:'right'}}>
                  <div style={{fontSize: 11, color:'var(--muted)', textTransform:'uppercase', letterSpacing:'0.08em', fontWeight: 600}}>From</div>
                  <div style={{fontFamily:'var(--serif)', fontSize: 22, fontWeight: 600, color:'var(--orange)'}}>{c.from}</div>
                </div>
              </div>
              <div style={{display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap: 10, marginTop: 16}}>
                {[{l:'HOMES', v: c.homes}, {l:'LEADS', v: c.leads}, {l:'SOLD', v: c.sold + '%'}].map(s => (
                  <div key={s.l} style={{padding:'10px 12px', background:'var(--bg-2)', border:'1px solid var(--border)', borderRadius: 8}}>
                    <div className="eyebrow" style={{fontSize: 9}}>{s.l}</div>
                    <div style={{fontFamily:'var(--serif)', fontSize: 20, fontWeight: 600, color:'var(--ink)', marginTop: 4}}>{s.v}</div>
                  </div>
                ))}
              </div>
              <div style={{display:'flex', gap: 6, marginTop: 14, flexWrap:'wrap'}}>
                {c.amenities.map(a => <span className="pill" key={a}>{a}</span>)}
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ═══ PIPELINE ════════════════════════════════════════════
function NealPipeline() {
  const d = window.NealData;
  const colors = { 'Inquiry': '#2e7bd6', 'Toured': '#15406c', 'Reserved': '#e3701b', 'Contract': '#d98a1f', 'Closed': '#2f9e6f' };
  return (
    <div data-screen-label="02 Pipeline">
      <div className="page-head">
        <div>
          <div className="eyebrow accent" style={{marginBottom: 8}}>$41.8M ACROSS 47 OPEN DEALS</div>
          <h1 className="page-title">Sales Pipeline</h1>
          <p className="page-sub">Drag buyers across stages. The assistant flags deals that have gone quiet and suggests the next touch.</p>
        </div>
        <div className="page-actions"><button className="btn">{NI.plus} New deal</button></div>
      </div>
      <div className="kanban">
        {Object.keys(d.pipeline).map(stage => (
          <div className="col" key={stage}>
            <div className="col-head">
              <div className="col-title"><span className="swatch" style={{background: colors[stage]}}/>{stage}</div>
              <div className="col-meta">{d.pipeline[stage].length}</div>
            </div>
            <div className="col-body">
              {d.pipeline[stage].map(c => (
                <div className="kcard" key={c.id}>
                  <div className="kcard-top">
                    <div><div className="kcard-name">{c.name}</div><div className="mono" style={{fontSize: 10.5, color:'var(--muted)'}}>{c.id}</div></div>
                    <div className="kcard-val">{c.val}</div>
                  </div>
                  <div className="kcard-asset">{c.asset}</div>
                  <div className="kcard-foot">
                    <div className="av" style={{background: c.color}}>{c.initials}</div>
                    {c.hot && <span className="pill hot" style={{fontSize: 10}}><span className="dot"/>HOT</span>}
                  </div>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, { NealDashboard, NealHomes, NealLeads, NealLeadDetail, NealCommunities, NealPipeline, NealWebActivity });
