// Neal Communities — Tours & Appts, Lead Forms, Website, Integrations

const OPS_ICONS = {
  cal: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" width="15" height="15"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>,
  video: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" width="15" height="15"><rect x="2" y="6" width="14" height="12" rx="2"/><path d="m22 8-6 4 6 4V8z"/></svg>,
  plug: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" width="15" height="15"><path d="M12 22v-5M9 8V2M15 8V2M6 8h12v5a6 6 0 0 1-12 0V8z"/></svg>,
};

function OpsStats({ stats }) {
  return (
    <div className="act-stats" style={{marginBottom: 20}}>
      {stats.map(s => (
        <div className="act-stat" key={s.l}>
          <div style={{display:'flex', alignItems:'baseline', gap: 8}}>
            <div className="act-stat-v">{s.v}</div>
            {s.delta && <span className="ops-delta">{s.delta}</span>}
          </div>
          <div className="act-stat-l">{s.l}</div>
        </div>
      ))}
    </div>
  );
}

function OpsSpark({ data, color }) {
  const max = Math.max(...data);
  const pts = data.map((v, i) => (i * (100 / (data.length - 1))) + ',' + (28 - (v / max) * 24));
  return (
    <svg viewBox="0 0 100 30" style={{width: 72, height: 22, display:'block'}} preserveAspectRatio="none">
      <polyline points={pts.join(' ')} fill="none" stroke={color || 'var(--orange)'} strokeWidth="2.5" strokeLinejoin="round" strokeLinecap="round"/>
    </svg>
  );
}

// ═══ TOURS & APPOINTMENTS ════════════════════════════════
function NealTours({ onSelectLead }) {
  const a = window.NealData.appts;
  const max = Math.max(...a.weekly.flatMap(w => [w.s, w.c]));
  return (
    <div data-screen-label="13 Tours">
      <div className="page-head">
        <div>
          <div className="eyebrow accent" style={{marginBottom: 8}}>28 SCHEDULED · 21 COMPLETED · LAST 30 DAYS</div>
          <h1 className="page-title">Tours &amp; Appointments</h1>
          <p className="page-sub">Model tours, virtual walk-throughs, design-center visits, and sales-gallery appointments — scheduled vs. completed, in one view.</p>
        </div>
        <div className="page-actions">
          <button className="btn ghost">{NI.sparkle} Fill open slots</button>
          <button className="btn">{NI.plus} Book appointment</button>
        </div>
      </div>

      <OpsStats stats={a.stats}/>

      <div className="grid" style={{gridTemplateColumns: '1.15fr 1fr', gap: 16, marginBottom: 16}}>
        {/* Scheduled vs completed chart */}
        <div className="card">
          <div className="card-head">
            <div className="card-title">Scheduled vs. completed</div>
            <div className="demo-legend" style={{margin: 0}}>
              <span><i style={{background:'var(--navy)'}}></i>Scheduled</span>
              <span><i style={{background:'var(--orange)'}}></i>Completed</span>
            </div>
          </div>
          <div className="card-body">
            <div className="appt-chart">
              {a.weekly.map((w, i) => (
                <div className="appt-col" key={w.w}>
                  <div className="appt-bars">
                    <div className="appt-bar s" style={{height: (w.s / max * 100) + '%'}}><span>{w.s}</span></div>
                    <div className="appt-bar c" style={{height: (w.c / max * 100) + '%'}}><span>{w.c}</span></div>
                  </div>
                  <div className="appt-week">{w.w}</div>
                </div>
              ))}
            </div>
            <div style={{fontSize: 11.5, color:'var(--muted)', marginTop: 12, display:'flex', alignItems:'center', gap: 6}}>
              {NI.sparkle} <span>Week of Jun 8 is in progress — 7 of 12 scheduled tours still ahead.</span>
            </div>
          </div>
        </div>

        {/* Recently completed */}
        <div className="card">
          <div className="card-head"><div className="card-title">Recently completed</div><span className="pill won" style={{fontSize: 10.5}}><span className="dot"/>75% show rate</span></div>
          <div className="card-body" style={{paddingTop: 8}}>
            {a.recent.map((r, i) => (
              <div key={i} style={{display:'flex', gap: 12, padding: '11px 0', borderBottom: i < a.recent.length-1 ? '1px solid var(--border)' : 0, alignItems:'flex-start'}}>
                <span className={'pill ' + r.tone} style={{fontSize: 10, flexShrink: 0, marginTop: 2}}><span className="dot"/>{r.tone === 'cold' ? 'No-show' : 'Done'}</span>
                <div style={{flex: 1, minWidth: 0}}>
                  <div style={{fontSize: 13, fontWeight: 700, color:'var(--ink)'}}>{r.buyer} <span style={{fontWeight: 500, color:'var(--muted)'}}>· {r.what}</span></div>
                  <div style={{fontSize: 11.5, color:'var(--muted)', marginTop: 2}}>→ {r.outcome}</div>
                </div>
                <span className="mono" style={{fontSize: 11, color:'var(--subtle)', flexShrink: 0}}>{r.time}</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Upcoming */}
      <div className="card" style={{padding: 0}}>
        <div className="card-head" style={{borderBottom: '1px solid var(--border)'}}><div className="card-title">Upcoming · next 7 days</div><button className="btn ghost sm">Open calendar</button></div>
        <table className="tbl">
          <thead><tr>
            <th style={{paddingLeft: 18}}>Buyer</th><th>Type</th><th>Home / community</th><th>When</th><th>Status</th>
            <th style={{textAlign:'right', paddingRight: 18}}>Note</th>
          </tr></thead>
          <tbody>
            {a.upcoming.map((u, i) => (
              <tr key={i}>
                <td style={{paddingLeft: 18}}>
                  <div className="av-row"><div className="av" style={{background: u.color}}>{u.initials}</div>
                    <div className="av-name">{u.buyer}</div></div>
                </td>
                <td><span className="pill" style={{fontSize: 10.5}}>{u.type === 'Virtual tour' ? OPS_ICONS.video : OPS_ICONS.cal}{u.type}</span></td>
                <td style={{fontSize: 12.5, color:'var(--text)'}}>{u.where}</td>
                <td className="mono" style={{fontSize: 12, color:'var(--ink)'}}>{u.when}</td>
                <td><span className={'pill ' + (u.status === 'Confirmed' ? 'won' : 'warm')}><span className="dot"/>{u.status}</span></td>
                <td style={{textAlign:'right', paddingRight: 18, fontSize: 12, color:'var(--muted)'}}>{u.note}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ═══ LEAD FORMS ══════════════════════════════════════════
function NealForms({ onOpenJourney }) {
  const f = window.NealData.forms;
  const d = window.NealData;
  return (
    <div data-screen-label="14 Forms">
      <div className="page-head">
        <div>
          <div className="eyebrow accent" style={{marginBottom: 8}}>6 ACTIVE FORMS · 412 SUBMISSIONS THIS MONTH</div>
          <h1 className="page-title">Lead Forms</h1>
          <p className="page-sub">Every form on nealcommunities.com routes straight into the CRM — scored by the assistant and, where it fits, enrolled into a journey automatically.</p>
        </div>
        <div className="page-actions">
          <button className="btn ghost">{NI.sparkle} Optimize a form</button>
          <button className="btn">{NI.plus} New form</button>
        </div>
      </div>

      <OpsStats stats={f.stats}/>

      <div className="grid" style={{gridTemplateColumns: '1.3fr 1fr', gap: 16}}>
        <div className="card" style={{padding: 0}}>
          <div className="card-head" style={{borderBottom: '1px solid var(--border)'}}><div className="card-title">Forms</div></div>
          <table className="tbl">
            <thead><tr>
              <th style={{paddingLeft: 18}}>Form</th><th>Subs · 30d</th><th>→ Tour</th><th>Trend</th>
              <th style={{textAlign:'right', paddingRight: 18}}>Feeds journey</th>
            </tr></thead>
            <tbody>
              {f.list.map(fm => {
                const j = fm.journey && d.journeys.find(x => x.id === fm.journey);
                return (
                  <tr key={fm.name}>
                    <td style={{paddingLeft: 18}}>
                      <div className="av-name">{fm.name}</div>
                      <div className="av-meta mono" style={{fontSize: 10.5}}>{fm.where}</div>
                    </td>
                    <td className="mono" style={{color:'var(--ink)', fontWeight: 600}}>{fm.subs}</td>
                    <td className="mono" style={{color: fm.conv >= 25 ? 'var(--good)' : 'var(--text)'}}>{fm.conv}%</td>
                    <td><OpsSpark data={fm.trend}/></td>
                    <td style={{textAlign:'right', paddingRight: 18}}>
                      {j ? <button className="act-journey" style={{marginTop: 0}} onClick={() => onOpenJourney && onOpenJourney(j.id)}>{NI.sparkle} {j.name}</button>
                         : <span style={{color:'var(--subtle)', fontSize: 12}}>—</span>}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>

        <div className="card" style={{padding: 0, alignSelf: 'start'}}>
          <div className="card-head" style={{borderBottom: '1px solid var(--border)'}}><div className="card-title">Latest submissions</div><span className="pill orange" style={{fontSize: 10.5}}>{NI.sparkle} Auto-routed</span></div>
          <div className="card-body" style={{paddingTop: 6}}>
            {f.recent.map((r, i) => {
              const j = r.journey && d.journeys.find(x => x.id === r.journey);
              return (
                <div key={i} style={{display:'flex', gap: 10, padding: '11px 0', borderBottom: i < f.recent.length-1 ? '1px solid var(--border)' : 0, alignItems:'center'}}>
                  <span className={'pill ' + (r.status === 'New' ? 'orange' : r.status === 'Routed' ? 'warm' : 'won')} style={{fontSize: 10, flexShrink: 0}}><span className="dot"/>{r.status}</span>
                  <div style={{flex: 1, minWidth: 0}}>
                    <div style={{fontSize: 12.5, fontWeight: 700, color:'var(--ink)'}}>{r.who}</div>
                    <div style={{fontSize: 11.5, color:'var(--muted)'}}>{r.form}{r.comm !== '—' ? ' · ' + r.comm : ''}{j ? ' · → ' + j.name : ''}</div>
                  </div>
                  <span className="mono" style={{fontSize: 11, color:'var(--subtle)', flexShrink: 0}}>{r.time}</span>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </div>
  );
}

// ═══ WEBSITE ═════════════════════════════════════════════
function NealWebsite() {
  const w = window.NealData.website;
  const maxV = Math.max(...w.pages.map(p => p.views));
  return (
    <div data-screen-label="15 Website">
      <div className="page-head">
        <div>
          <div className="eyebrow accent" style={{marginBottom: 8}}>NEALCOMMUNITIES.COM · LIVE TWO-WAY SYNC</div>
          <h1 className="page-title">Website</h1>
          <p className="page-sub">Traffic, top pages, and lead conversion — with inventory, pricing, and forms synced both ways with nealcommunities.com.</p>
        </div>
        <div className="page-actions">
          <button className="btn ghost">Open GA4</button>
          <button className="btn navy">Visit site</button>
        </div>
      </div>

      <OpsStats stats={w.stats}/>

      <div className="grid" style={{gridTemplateColumns: '1.3fr 1fr', gap: 16}}>
        <div className="card" style={{padding: 0}}>
          <div className="card-head" style={{borderBottom: '1px solid var(--border)'}}><div className="card-title">Top pages · 30 days</div></div>
          <table className="tbl">
            <thead><tr>
              <th style={{paddingLeft: 18}}>Page</th><th>Views</th><th></th>
              <th style={{textAlign:'right', paddingRight: 18}}>Leads</th>
            </tr></thead>
            <tbody>
              {w.pages.map(p => (
                <tr key={p.path}>
                  <td style={{paddingLeft: 18}} className="mono"><span style={{fontSize: 12, color:'var(--ink)'}}>{p.path}</span></td>
                  <td className="mono" style={{color:'var(--ink)'}}>{p.views.toLocaleString()}</td>
                  <td style={{width: 130}}>
                    <div style={{height: 6, background:'var(--bg-2)', borderRadius: 3, overflow:'hidden'}}>
                      <div style={{width: (p.views/maxV*100) + '%', height:'100%', background:'var(--navy)'}}></div>
                    </div>
                  </td>
                  <td className="mono" style={{textAlign:'right', paddingRight: 18, color:'var(--orange)', fontWeight: 600}}>{p.leads}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div style={{display:'flex', flexDirection:'column', gap: 16}}>
          <div className="card">
            <div className="card-head"><div className="card-title">Traffic sources</div></div>
            <div className="card-body" style={{paddingTop: 8}}>
              {w.sources.map(s => (
                <div key={s.name} style={{display:'grid', gridTemplateColumns:'110px 1fr 38px', gap: 10, alignItems:'center', padding: '6px 0'}}>
                  <div style={{fontSize: 12, fontWeight: 600, color:'var(--ink)'}}>{s.name}</div>
                  <div style={{height: 8, background:'var(--bg-2)', borderRadius: 4, overflow:'hidden'}}>
                    <div style={{width: s.pct + '%', height:'100%', borderRadius: 4, background: s.name === 'Journey emails' ? 'var(--orange)' : 'var(--navy)'}}></div>
                  </div>
                  <div className="mono" style={{fontSize: 11.5, color:'var(--muted)', textAlign:'right'}}>{s.pct}%</div>
                </div>
              ))}
            </div>
          </div>
          <div className="card">
            <div className="card-head"><div className="card-title">Site sync</div><span className="pill won" style={{fontSize: 10.5}}><span className="dot"/>Healthy</span></div>
            <div className="card-body" style={{paddingTop: 6}}>
              {w.sync.map((s, i) => (
                <div key={s.what} style={{display:'flex', justifyContent:'space-between', padding: '9px 0', borderBottom: i < w.sync.length-1 ? '1px solid var(--border)' : 0}}>
                  <span style={{fontSize: 12.5, fontWeight: 600, color:'var(--ink)'}}>{s.what}</span>
                  <span style={{fontSize: 11.5, color:'var(--good)', fontWeight: 600}}>{s.state}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ═══ INTEGRATIONS ════════════════════════════════════════
function NealIntegrations() {
  const groups = window.NealData.integrations;
  const total = groups.reduce((n, g) => n + g.items.length, 0);
  return (
    <div data-screen-label="16 Integrations">
      <div className="page-head">
        <div>
          <div className="eyebrow accent" style={{marginBottom: 8}}>{total} CONNECTED SOURCES · AND GROWING</div>
          <h1 className="page-title">Integrations</h1>
          <p className="page-sub">Every source the Neal Assistant can query — ads, analytics, portals, CRM, phones, and builder operations. Ask a question; it pulls from all of them.</p>
        </div>
        <div className="page-actions">
          <button className="btn">{NI.plus} Request an integration</button>
        </div>
      </div>

      <div className="card insight-strip" style={{marginBottom: 24, 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)'}}>
          <strong>“What was our cost per lead in Q2?”</strong> — answers like this combine Google Ads, Meta, GA4, and the CRM in one pass. The more sources connected, the smarter the assistant gets.
        </div>
        <button className="btn sm">{NI.sparkle} Try it</button>
      </div>

      {groups.map(g => (
        <div key={g.group} style={{marginBottom: 26}}>
          <div className="eyebrow" style={{marginBottom: 12}}>{g.group.toUpperCase()}</div>
          <div className="int-grid">
            {g.items.map(it => (
              <div className="card int-card" key={it.name}>
                <div className="int-logo" style={{background: it.color}}>{it.abbr}</div>
                <div style={{flex: 1, minWidth: 0}}>
                  <div className="int-name">{it.name}</div>
                  <div className="int-desc">{it.desc}</div>
                </div>
                <div className="int-foot">
                  <span className="int-status"><span className="dot"></span>Connected</span>
                  <span className="int-sync">{it.sync}</span>
                </div>
              </div>
            ))}
          </div>
        </div>
      ))}

      <div className="int-request">
        <div style={{fontFamily:'var(--serif)', fontSize: 18, fontWeight: 600, color:'var(--ink)'}}>And growing…</div>
        <div style={{fontSize: 12.5, color:'var(--muted)', marginTop: 4}}>Need another source? Most integrations connect in under a week.</div>
        <button className="btn ghost sm" style={{marginTop: 12}}>{NI.plus} Request an integration</button>
      </div>
    </div>
  );
}

Object.assign(window, { NealTours, NealForms, NealWebsite, NealIntegrations });
