// Neal Communities — Neal Assistant demo: Peak Seven prompt examples
// Overrides NealCopilot from neal-shell.jsx (loaded after it).

// ─── Demo answer data ────────────────────────────────────
const NEAL_DEMOS = [
  {
    id: 'q2-report',
    prompt: 'Please pull a lead and sales report for Q2 2025 compared to Q2 2026. I would like to know how many leads we generated and by what channel and what was our cost per lead… analyze and let me know the largest difference you see.',
    short: 'Q2 2025 vs Q2 2026 lead & sales report',
  },
  {
    id: 'ytd-graph',
    prompt: 'Please show me a graph that shows our YTD home sales compared to our google and meta leads generated during the same time period… analyze and highlight any unique data points you see.',
    short: 'YTD home sales vs Google & Meta leads',
  },
  {
    id: 'north-conversion',
    prompt: 'What sales teams have the highest sales conversion to foot traffic in the north?',
    short: 'Top converting sales teams · North',
  },
  {
    id: 'lead-timing',
    prompt: 'What time of day and day of the week do we get the most leads? Break it out by Google vs Realtor.com.',
    short: 'Lead timing · Google vs Realtor.com',
  },
  {
    id: 'permits',
    prompt: 'How many home start permits do we have for Q3 in the south division?',
    short: 'Q3 home start permits · South division',
  },
  {
    id: 'skysail-inventory',
    prompt: 'Show me a list of the oldest inventory homes in SkySail and what incentives do we have on them right now. Also include phone calls received in the last 90 days.',
    short: 'Oldest SkySail inventory + incentives',
  },
  {
    id: 'composite-north',
    prompt: 'Please give me a composite report illustrating Total leads, Qualified leads, Appointments, and Contracts signed for the North division YTD.',
    short: 'Composite funnel report · North YTD',
  },
];

// ─── Small chart primitives ──────────────────────────────
function DemoLegend({ items }) {
  return (
    <div className="demo-legend">
      {items.map(it => <span key={it.label}><i style={{background: it.color}}/>{it.label}</span>)}
    </div>
  );
}

function PairBars({ rows, aLabel, bLabel, max }) {
  const m = max || Math.max(...rows.flatMap(r => [r.a, r.b]));
  return (
    <div className="pairbars">
      <DemoLegend items={[{label: aLabel, color: 'var(--navy-2, #2f6fae)'}, {label: bLabel, color: 'var(--orange)'}]}/>
      {rows.map(r => (
        <div className="pairbar-row" key={r.label}>
          <div className="pairbar-label">{r.label}</div>
          <div className="pairbar-tracks">
            <div className="pairbar-track"><div className="pairbar-fill a" style={{width: (r.a/m*100) + '%'}}/><span className="mono">{r.a.toLocaleString()}</span></div>
            <div className="pairbar-track"><div className="pairbar-fill b" style={{width: (r.b/m*100) + '%'}}/><span className="mono">{r.b.toLocaleString()}</span></div>
          </div>
          {r.note && <div className={'pairbar-note' + (r.hot ? ' hot' : '')}>{r.note}</div>}
        </div>
      ))}
    </div>
  );
}

function ComboChart() {
  // Jan–Jun: sales (bars), google leads, meta leads (lines, scaled /10)
  const months = ['Jan','Feb','Mar','Apr','May','Jun'];
  const sales  = [18, 22, 31, 26, 24, 29];
  const google = [42, 48, 71, 58, 52, 64];   // tens of leads
  const meta   = [35, 39, 44, 47, 28, 33];
  const W = 420, H = 150, P = 26;
  const x = (i) => P + i * ((W - P*2) / 5);
  const yS = (v) => H - 22 - (v / 35) * (H - 50);
  const yL = (v) => H - 22 - (v / 80) * (H - 50);
  const path = (arr, fn) => arr.map((v, i) => (i ? 'L' : 'M') + x(i) + ' ' + fn(v)).join(' ');
  return (
    <div>
      <DemoLegend items={[
        {label: 'Home sales', color: 'var(--orange)'},
        {label: 'Google leads (×10)', color: '#2f6fae'},
        {label: 'Meta leads (×10)', color: '#9c6fcf'},
      ]}/>
      <svg viewBox={'0 0 ' + W + ' ' + H} style={{width: '100%', height: 'auto', display: 'block'}}>
        {months.map((mo, i) => (
          <g key={mo}>
            <rect x={x(i)-9} y={yS(sales[i])} width="18" height={H - 22 - yS(sales[i])} rx="3" fill="var(--orange)" opacity="0.9"/>
            <text x={x(i)} y={H - 8} textAnchor="middle" fontSize="9.5" fill="var(--muted)" fontFamily="var(--mono)">{mo}</text>
            <text x={x(i)} y={yS(sales[i]) - 4} textAnchor="middle" fontSize="9" fill="var(--orange)" fontWeight="700" fontFamily="var(--mono)">{sales[i]}</text>
          </g>
        ))}
        <path d={path(google, yL)} fill="none" stroke="#2f6fae" strokeWidth="2" strokeLinecap="round"/>
        <path d={path(meta, yL)} fill="none" stroke="#9c6fcf" strokeWidth="2" strokeDasharray="4 3" strokeLinecap="round"/>
        {google.map((v, i) => <circle key={'g'+i} cx={x(i)} cy={yL(v)} r="2.6" fill="#2f6fae"/>)}
        {meta.map((v, i) => <circle key={'m'+i} cx={x(i)} cy={yL(v)} r="2.6" fill="#9c6fcf"/>)}
        <circle cx={x(2)} cy={yL(google[2])} r="6" fill="none" stroke="var(--orange)" strokeWidth="1.6"/>
        <circle cx={x(4)} cy={yL(meta[4])} r="6" fill="none" stroke="var(--orange)" strokeWidth="1.6"/>
      </svg>
    </div>
  );
}

function RankBars({ rows, unit }) {
  const m = Math.max(...rows.map(r => r.v));
  return (
    <div className="rankbars">
      {rows.map((r, i) => (
        <div className="rankbar" key={r.label}>
          <div className="rankbar-rank mono">{i + 1}</div>
          <div style={{flex: 1, minWidth: 0}}>
            <div className="rankbar-head"><span>{r.label}</span><span className="mono" style={{color: i === 0 ? 'var(--orange)' : 'var(--ink)'}}>{r.v}{unit}</span></div>
            <div className="rankbar-track"><div className={'rankbar-fill' + (i === 0 ? ' top' : '')} style={{width: (r.v/m*100) + '%'}}/></div>
            <div className="rankbar-meta">{r.meta}</div>
          </div>
        </div>
      ))}
    </div>
  );
}

function HeatGrid() {
  const days = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'];
  const slots = ['8–11a','11a–2p','2–5p','5–8p'];
  const google = [ [2,4,3,1],[3,5,3,2],[3,5,4,2],[2,4,3,2],[2,3,2,1],[1,2,1,1],[1,1,1,0] ];
  const realtor = [ [1,2,2,2],[1,2,2,3],[1,2,2,3],[1,2,3,3],[2,3,3,2],[4,5,4,2],[4,5,3,1] ];
  const cell = (v, hue) => ({ background: v === 0 ? 'var(--bg-2)' : `rgba(${hue}, ${0.12 + v * 0.16})` });
  return (
    <div className="heat-wrap">
      {[{name: 'Google', data: google, hue: '47,111,174'}, {name: 'Realtor.com', data: realtor, hue: '227,112,27'}].map(src => (
        <div key={src.name}>
          <div className="heat-title">{src.name}</div>
          <div className="heat-grid">
            <div className="heat-corner"/>
            {slots.map(s => <div className="heat-col" key={s}>{s}</div>)}
            {days.map((d, di) => (
              <React.Fragment key={d}>
                <div className="heat-row">{d}</div>
                {src.data[di].map((v, si) => <div className="heat-cell" key={si} style={cell(v, src.hue)}/>)}
              </React.Fragment>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
}

function MiniFunnel({ rows }) {
  return (
    <div className="mini-funnel">
      {rows.map((r, i) => (
        <div className="mf-row" key={r.label}>
          <div className="mf-label">{r.label}</div>
          <div className="mf-track"><div className={'mf-fill' + (i === rows.length-1 ? ' last' : '')} style={{width: r.pct + '%'}}/></div>
          <div className="mf-v mono">{r.v.toLocaleString()}</div>
          <div className="mf-pct mono">{r.pct}%</div>
        </div>
      ))}
    </div>
  );
}

function DemoTable({ cols, rows }) {
  return (
    <table className="demo-tbl">
      <thead><tr>{cols.map(c => <th key={c}>{c}</th>)}</tr></thead>
      <tbody>
        {rows.map((r, i) => <tr key={i}>{r.map((cell, j) => <td key={j}>{cell}</td>)}</tr>)}
      </tbody>
    </table>
  );
}

function Takeaways({ items }) {
  return (
    <div className="takeaways">
      <div className="takeaways-head">{NI.sparkle} WHAT STANDS OUT</div>
      <ul>{items.map((t, i) => <li key={i}>{t}</li>)}</ul>
    </div>
  );
}

// ─── Answer renderers per demo ───────────────────────────
function DemoAnswer({ id }) {
  switch (id) {
    case 'q2-report': return (
      <>
        <div className="msg-body">Here's your Q2 lead &amp; sales report, year over year. Leads by channel with cost per lead:</div>
        <div className="ai-card">
          <div className="ai-card-head"><span>Leads by channel · Q2 2025 vs Q2 2026</span><span style={{color:'var(--good)'}}>+19% total</span></div>
          <div className="ai-card-body" style={{padding: 14}}>
            <PairBars aLabel="Q2 2025" bLabel="Q2 2026" rows={[
              { label: 'Google', a: 412, b: 581, note: 'CPL $58 → $39', hot: true },
              { label: 'Meta', a: 348, b: 322, note: 'CPL $44 → $51' },
              { label: 'Realtor.com', a: 296, b: 287, note: 'CPL $71 → $69' },
              { label: 'Organic / Direct', a: 188, b: 246, note: 'CPL —' },
              { label: 'Referral', a: 94, b: 121, note: 'CPL $12 → $11' },
            ]}/>
            <div className="demo-divider"/>
            <div className="demo-stats">
              <div><div className="ds-v">1,338 → 1,557</div><div className="ds-l">Total leads</div></div>
              <div><div className="ds-v">$52 → $43</div><div className="ds-l">Blended CPL</div></div>
              <div><div className="ds-v">117 → 139</div><div className="ds-l">Homes sold</div></div>
            </div>
          </div>
        </div>
        <Takeaways items={[
          <><strong>Largest difference: Google.</strong> Leads up 41% while cost per lead fell $19 (−33%) — the Performance Max restructure in March is paying for itself.</>,
          <>Meta is moving the wrong direction on both axes: fewer leads at a higher CPL. Worth a creative refresh before Q3.</>,
        ]}/>
      </>
    );
    case 'ytd-graph': return (
      <>
        <div className="msg-body">YTD home sales plotted against Google and Meta lead volume, January through June:</div>
        <div className="ai-card">
          <div className="ai-card-head"><span>Home sales vs. paid leads · YTD 2026</span><span>Jan – Jun</span></div>
          <div className="ai-card-body" style={{padding: 14}}><ComboChart/></div>
        </div>
        <Takeaways items={[
          <><strong>March is the outlier</strong> — Google leads spiked to 710 and sales followed to 31 closings, your best month. That was the "Escape the Gray" campaign window.</>,
          <><strong>May is the interesting one:</strong> Meta leads dropped 40% but sales barely dipped — Meta volume isn't driving closings the way Google volume is.</>,
          <>Sales trail lead spikes by roughly 4–6 weeks. June's Google recovery suggests a strong July.</>,
        ]}/>
      </>
    );
    case 'north-conversion': return (
      <>
        <div className="msg-body">Conversion from foot traffic to contract, North division sales teams, trailing 90 days:</div>
        <div className="ai-card">
          <div className="ai-card-head"><span>Foot traffic → contract · North</span><span>Trailing 90 days</span></div>
          <div className="ai-card-body" style={{padding: 14}}>
            <RankBars unit="%" rows={[
              { label: 'Lakewood Ranch · Indigo team', v: 14.2, meta: '312 walk-ins · 44 contracts' },
              { label: 'Bradenton · Esplanade team', v: 11.8, meta: '288 walk-ins · 34 contracts' },
              { label: 'Lakewood Ranch · Palm Grove team', v: 10.4, meta: '356 walk-ins · 37 contracts' },
              { label: 'Parrish · Crosswind team', v: 8.1, meta: '197 walk-ins · 16 contracts' },
            ]}/>
          </div>
        </div>
        <Takeaways items={[
          <><strong>The Indigo team leads at 14.2%</strong> — nearly double Parrish. Their model-home tour script was refreshed in April; worth rolling out division-wide.</>,
          <>Palm Grove has the most foot traffic but mid-pack conversion — a staffing opportunity on weekends.</>,
        ]}/>
      </>
    );
    case 'lead-timing': return (
      <>
        <div className="msg-body">Lead volume by day of week and time of day, split by source. Darker = more leads:</div>
        <div className="ai-card">
          <div className="ai-card-head"><span>When leads arrive · last 8 weeks</span><span>All communities</span></div>
          <div className="ai-card-body" style={{padding: 14}}><HeatGrid/></div>
        </div>
        <Takeaways items={[
          <><strong>Google peaks Tue–Wed, 11am–2pm</strong> — research-mode buyers on lunch breaks. Make sure OSC coverage is full mid-week, midday.</>,
          <><strong>Realtor.com flips to the weekend:</strong> Sat–Sun mornings, 8–11am — active shoppers planning same-day visits. Speed-to-lead matters most here.</>,
        ]}/>
      </>
    );
    case 'permits': return (
      <>
        <div className="msg-body">South division has <strong>38 home start permits</strong> on file for Q3 2026:</div>
        <div className="ai-card">
          <div className="ai-card-head"><span>Q3 2026 start permits · South division</span><span style={{color:'var(--good)'}}>+6 vs Q2</span></div>
          <div className="ai-card-body" style={{padding: 14}}>
            <div className="demo-stats" style={{marginBottom: 14}}>
              <div><div className="ds-v big">38</div><div className="ds-l">Total permits</div></div>
              <div><div className="ds-v">Jul 14 · Aug 13 · Sep 11</div><div className="ds-l">By month</div></div>
            </div>
            <DemoTable cols={['Community', 'Permits', 'Status']} rows={[
              ['SkySail · Naples', '17', <span className="pill won" key="a"><span className="dot"/>12 approved</span>],
              ['Wellen Park · Venice', '12', <span className="pill warm" key="b"><span className="dot"/>4 in review</span>],
              ['Boca Royale · Englewood', '9', <span className="pill won" key="c"><span className="dot"/>All approved</span>],
            ]}/>
          </div>
        </div>
        <Takeaways items={[
          <>SkySail carries 45% of Q3 starts — aligned with the lagoon phase-2 release.</>,
          <>4 Wellen Park permits are still in county review; 2 are past the 21-day target. Flagged for follow-up.</>,
        ]}/>
      </>
    );
    case 'skysail-inventory': return (
      <>
        <div className="msg-body">The 4 oldest inventory homes in SkySail, with current incentives and 90-day call volume:</div>
        <div className="ai-card">
          <div className="ai-card-head"><span>Aging inventory · SkySail</span><span>Sorted by days on market</span></div>
          <div className="ai-card-body" style={{padding: 14}}>
            <DemoTable cols={['Home', 'DOM', 'Incentive', 'Calls 90d']} rows={[
              [<span key="1"><strong>Winslow</strong> · HS 305</span>, <span className="mono hot-dom" key="1d">148</span>, '$15k closing + rate buy-down', <span className="mono" key="1c">6</span>],
              [<span key="2"><strong>Augusta</strong> · HS 21</span>, <span className="mono hot-dom" key="2d">121</span>, '$8k design credit', <span className="mono" key="2c">14</span>],
              [<span key="3"><strong>Augusta</strong> · HS 33</span>, <span className="mono" key="3d">96</span>, '$8k design credit', <span className="mono" key="3c">11</span>],
              [<span key="4"><strong>Winslow</strong> · HS 290</span>, <span className="mono" key="4d">82</span>, 'Rate buy-down only', <span className="mono" key="4c">9</span>],
            ]}/>
          </div>
        </div>
        <Takeaways items={[
          <><strong>Winslow HS 305 is the problem child:</strong> 148 days, biggest incentive, fewest calls. The homesite (no lagoon view) is the likely drag — consider a price reposition instead of stacking incentives.</>,
          <>Augusta HS 21 gets the most calls but isn't converting — 14 calls, zero tours booked. I can pull the call summaries if you want to hear why.</>,
        ]}/>
      </>
    );
    case 'composite-north': return (
      <>
        <div className="msg-body">Composite report for the North division, year to date:</div>
        <div className="ai-card">
          <div className="ai-card-head"><span>North division composite · YTD 2026</span><span>Jan 1 – Jun 10</span></div>
          <div className="ai-card-body" style={{padding: 14}}>
            <MiniFunnel rows={[
              { label: 'Total leads', v: 3184, pct: 100 },
              { label: 'Qualified leads', v: 1276, pct: 40 },
              { label: 'Appointments', v: 411, pct: 13 },
              { label: 'Contracts signed', v: 124, pct: 3.9 },
            ]}/>
          </div>
        </div>
        <Takeaways items={[
          <>Lead → qualified (40%) and appointment → contract (30%) are both above target. The soft spot is <strong>qualified → appointment at 32%</strong> — about 90 qualified buyers a month never get to a model home.</>,
          <>Want this as a weekly email to the division leads? I can set that up.</>,
        ]}/>
      </>
    );
    default: return <div className="msg-body">I don't have a demo answer for that yet.</div>;
  }
}

// ─── The upgraded copilot drawer ─────────────────────────
function NealCopilot({ context, open, onClose }) {
  const [messages, setMessages] = React.useState([]);   // {role:'user'|'assistant', id?, text?}
  const [thinking, setThinking] = React.useState(false);
  const [played, setPlayed] = React.useState([]);
  const [input, setInput] = React.useState('');
  const streamRef = React.useRef(null);
  const timers = React.useRef([]);
  React.useEffect(() => () => timers.current.forEach(clearTimeout), []);

  const scrollDown = () => {
    const el = streamRef.current;
    if (el) requestAnimationFrame(() => { el.scrollTop = el.scrollHeight; });
  };
  React.useEffect(scrollDown, [messages, thinking]);

  const play = (demo) => {
    if (thinking) return;
    setMessages(m => [...m, { role: 'user', text: demo.prompt }]);
    setThinking(true);
    timers.current.push(setTimeout(() => {
      setThinking(false);
      setMessages(m => [...m, { role: 'assistant', id: demo.id }]);
      setPlayed(p => p.includes(demo.id) ? p : [...p, demo.id]);
    }, 1300));
  };

  // Next unplayed prompt — surfaced inline after each answer so the
  // presenter never has to scroll back up.
  const lastMsg = messages[messages.length - 1];
  const nextDemo = (!thinking && lastMsg && lastMsg.role === 'assistant')
    ? NEAL_DEMOS.find(d => !played.includes(d.id))
    : null;

  const sendFree = () => {
    const text = input.trim();
    if (!text || thinking) return;
    setInput('');
    const match = NEAL_DEMOS.find(d => !played.includes(d.id));
    setMessages(m => [...m, { role: 'user', text }]);
    setThinking(true);
    timers.current.push(setTimeout(() => {
      setThinking(false);
      setMessages(m => [...m, { role: 'assistant', id: 'freeform', text }]);
    }, 1100));
  };

  return (
    <>
      <div className={'copilot-scrim' + (open ? ' open' : '')} onClick={onClose}></div>
      <aside className={'copilot' + (open ? ' open' : '')}>
        <div className="copilot-head">
          <div className="ai-bug">{NI.sparkle}</div>
          <div style={{flex: 1, minWidth: 0}}>
            <div className="copilot-title">Neal Assistant</div>
            <div className="copilot-sub">Reports · Matching · AI</div>
          </div>
          {messages.length > 0 && (
            <button className="copilot-reset" onClick={() => { setMessages([]); setPlayed([]); setThinking(false); }}>Reset demo</button>
          )}
          <div className="copilot-close" onClick={onClose}>
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" width="14" height="14"><path d="M18 6 6 18M6 6l12 12"/></svg>
          </div>
        </div>

        <div className="copilot-context">
          <span className="dot"></span>
          Context · {context}
        </div>

        <div className="copilot-stream" ref={streamRef}>
          {/* Welcome + prompt menu */}
          <div className="msg-block">
            <div className="msg-meta"><span className="role">Assistant</span><span>· now</span></div>
            <div className="msg-body">
              Good morning, Jasmine. I'm connected to your leads, inventory, permits, call logs, and ad platforms. Ask me anything — or try one of these:
            </div>
            <div className="demo-prompts">
              {NEAL_DEMOS.map(d => (
                <button key={d.id} className={'demo-prompt' + (played.includes(d.id) ? ' played' : '')} onClick={() => play(d)}>
                  <span className="dp-ic">{played.includes(d.id)
                    ? <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" width="12" height="12"><path d="M20 6 9 17l-5-5"/></svg>
                    : NI.sparkle}</span>
                  <span className="dp-text">{d.short}</span>
                  <span className="dp-go">{NI.chevron}</span>
                </button>
              ))}
            </div>
          </div>

          {messages.map((msg, i) => (
            <div className="msg-block" key={i}>
              <div className="msg-meta"><span className="role">{msg.role === 'user' ? 'You' : 'Assistant'}</span><span>· now</span></div>
              {msg.role === 'user'
                ? <div className="msg-body user">{msg.text}</div>
                : msg.id === 'freeform'
                ? <div className="msg-body">Good question — in this demo I answer the seven Peak Seven example prompts above. Pick one and I'll pull the real report.</div>
                : <DemoAnswer id={msg.id}/>}
            </div>
          ))}

          {thinking && (
            <div className="msg-block">
              <div className="msg-meta"><span className="role">Assistant</span><span>· thinking</span></div>
              <div className="thinking">
                <span className="t-dot"></span><span className="t-dot"></span><span className="t-dot"></span>
                <span className="t-label">Querying CRM, ad platforms &amp; call logs…</span>
              </div>
            </div>
          )}

          {nextDemo && (
            <div className="next-up">
              <div className="next-up-label">{NI.sparkle} UP NEXT · {played.length} OF {NEAL_DEMOS.length} SHOWN</div>
              <button className="demo-prompt next" onClick={() => play(nextDemo)}>
                <span className="dp-ic">{NI.sparkle}</span>
                <span className="dp-text">{nextDemo.short}</span>
                <span className="dp-go">{NI.chevron}</span>
              </button>
            </div>
          )}
          {!nextDemo && !thinking && lastMsg && lastMsg.role === 'assistant' && played.length === NEAL_DEMOS.length && (
            <div className="next-up">
              <div className="next-up-label">{NI.sparkle} THAT'S ALL {NEAL_DEMOS.length} — DEMO COMPLETE</div>
            </div>
          )}
        </div>

        <div className="copilot-foot">
          <div className="copilot-input">
            <span style={{color: 'var(--subtle)'}}>{NI.paperclip}</span>
            <input
              placeholder="Ask about leads, sales, permits, inventory…"
              value={input}
              onChange={e => setInput(e.target.value)}
              onKeyDown={e => { if (e.key === 'Enter') sendFree(); }}
            />
            <div className="send" onClick={sendFree}>{NI.send}</div>
          </div>
          <div className="hint"><span>⌘ + J to summon</span><span style={{marginLeft: 'auto'}}>Connected · CRM · Google Ads · Meta · CallRail</span></div>
        </div>
      </aside>
    </>
  );
}

Object.assign(window, { NealCopilot, NEAL_DEMOS });
