// Internal RCG-only views: Prospect Research, RCG Performance, Client Roster, Connect Sources.

const { useState: iuState, useMemo: iuMemo } = React;
const IRC = window.Recharts;
const I_BRAND_RED = '#BE2E2B';
const I_RICH_BLACK = '#1A1919';
const I_DARK_GREEN = '#315A49';
const I_DARK_BLUE = '#29254E';
const I_DARK_GRAY = '#5B5C5B';
const I_SOFT_RULE = 'rgba(26,25,25,0.12)';

// ── PROSPECT RESEARCH ────────────────────────────────────
function ProspectResearchTab({ pushToast }) {
  const [industry, setIndustry] = iuState('All');
  const [size, setSize] = iuState('All');
  const [status, setStatus] = iuState('All');
  const [minScore, setMinScore] = iuState(0);
  const [openId, setOpenId] = iuState(null);
  const [notes, setNotes] = iuState({});

  const prospects = window.RCG_PROSPECTS;
  const industries = ['All', ...new Set(prospects.map((p) => p.industry))];
  const sizes = ['All', 'Small', 'Mid-market', 'Large'];
  const statuses = ['All', 'New', 'Researching', 'Pursuing', 'Passed'];

  const filtered = prospects.filter((p) => {
    if (industry !== 'All' && p.industry !== industry) return false;
    if (status !== 'All' && p.status !== status) return false;
    if (minScore > 0 && p.score < minScore) return false;
    return true;
  });

  const open = prospects.find((p) => p.id === openId);

  return (
    <div className="tab-content" style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
      <TabHeader title="Prospect Research" desc="Pipeline of accounts worth pursuing. Detected stack, recent signals, and our take on the wedge." />

      {/* Filter bar */}
      <Card pad="lg" style={{ padding: '18px 22px' }}>
        <div style={{ display: 'flex', gap: 24, alignItems: 'center', flexWrap: 'wrap' }}>
          <FilterPicker label="Industry" value={industry} options={industries} onChange={setIndustry} />
          <FilterPicker label="Company size" value={size} options={sizes} onChange={setSize} />
          <FilterPicker label="Status" value={status} options={statuses} onChange={setStatus} />
          <div className="field" style={{ minWidth: 180 }}>
            <label>Min problem score <span style={{ color: 'var(--rich-black)', fontWeight: 500 }}>{minScore}</span></label>
            <div className="slider-row">
              <input type="range" min="0" max="100" step="1" value={minScore} onChange={(e) => setMinScore(+e.target.value)} />
            </div>
          </div>
          <div style={{ flex: 1 }} />
          <div className="meta">{filtered.length} of {prospects.length} accounts</div>
        </div>
      </Card>

      <Card pad="lg" style={{ padding: 0 }}>
        <table className="tbl">
          <thead>
            <tr>
              <th>Company</th>
              <th>Industry</th>
              <th>Size</th>
              <th>Detected Stack</th>
              <th>Last Activity</th>
              <th className="num-head">Problem Score</th>
              <th>Status</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map((p) => (
              <tr key={p.id} className="clickable" onClick={() => setOpenId(p.id)}>
                <td className="strong">{p.company}</td>
                <td className="muted">{p.industry}</td>
                <td className="muted">{p.size}</td>
                <td style={{ fontSize: 11.5, color: 'var(--ink-muted)', maxWidth: 240 }}>{p.stack}</td>
                <td style={{ fontSize: 12, color: 'var(--ink-muted)', maxWidth: 220 }}>{p.activity}</td>
                <td className="num"><ScorePill score={p.score} /></td>
                <td><StatusChip status={p.status} /></td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>

      <SidePanel
        open={!!open}
        onClose={() => setOpenId(null)}
        title={open ? open.company : ''}
      >
        {open && (
          <React.Fragment>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap' }}>
              <StatusChip status={open.status} />
              <span className="meta">{open.industry} · {open.size}</span>
              <span style={{ marginLeft: 'auto' }}><ScorePill score={open.score} /></span>
            </div>

            <div>
              <p className="card-eyebrow">Summary</p>
              <p style={{ fontSize: 14, lineHeight: 1.6, color: 'var(--rich-black)', margin: 0 }}>
                {open.summary}
              </p>
            </div>

            <div>
              <p className="card-eyebrow">Detected stack</p>
              <p style={{ fontSize: 13, color: 'var(--rich-black)', margin: 0 }}>{open.stack}</p>
            </div>

            {open.signals && open.signals.length > 0 && (
              <div>
                <p className="card-eyebrow">Recent signals · last 90 days</p>
                <div className="timeline">
                  {open.signals.map((s, i) => (
                    <div key={i} className={`timeline-item ${s.red ? 'red' : ''}`}>
                      <div className="when">{s.when}</div>
                      <div className="what">{s.what}</div>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {open.take && (
              <div style={{ background: 'var(--paper)', padding: '20px 22px', borderLeft: '2px solid ' + I_BRAND_RED }}>
                <p className="card-eyebrow" style={{ color: I_BRAND_RED }}>RCG take</p>
                <p style={{ fontSize: 14, lineHeight: 1.6, color: 'var(--rich-black)', margin: 0, fontFamily: 'var(--sans)' }}>
                  {open.take}
                </p>
              </div>
            )}

            <div className="field">
              <label>Internal notes</label>
              <textarea
                rows={4}
                placeholder="Add a note for the team."
                value={notes[open.id] || ''}
                onChange={(e) => setNotes({ ...notes, [open.id]: e.target.value })}
              />
            </div>

            <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
              <Pill variant="red" onClick={() => pushToast(`${open.company} moved to Pursuing.`, 'success')}>
                Move to Pursuing
              </Pill>
              <Pill variant="outline" onClick={() => pushToast(`${open.company} marked as Passed.`, 'success')}>
                Mark as Passed
              </Pill>
              <Pill variant="outline" onClick={() => pushToast('Outreach email drafted.', 'success')}>
                Generate Outreach
              </Pill>
            </div>
          </React.Fragment>
        )}
      </SidePanel>
    </div>
  );
}
window.ProspectResearchTab = ProspectResearchTab;

function FilterPicker({ label, value, options, onChange }) {
  return (
    <div className="field">
      <label>{label}</label>
      <select
        value={value}
        onChange={(e) => onChange(e.target.value)}
        style={{ minWidth: 160, padding: '9px 14px' }}
      >
        {options.map((o) => <option key={o} value={o}>{o}</option>)}
      </select>
    </div>
  );
}

// ── RCG PERFORMANCE ──────────────────────────────────────
function RcgPerformanceTab() {
  const perf = window.RCG_PERF;
  return (
    <div className="tab-content" style={{ display: 'flex', flexDirection: 'column', gap: 28 }}>
      <TabHeader title="RCG Performance" desc="The agency, looking at itself. MRR, retention, utilization, NPS." />

      <div className="kpi-grid">
        <KpiCell label="Active Clients" value={perf.kpis.activeClients} delta={14.3} />
        <KpiCell label="MRR" value={fmtMoney(perf.kpis.mrr, { compact: true })} delta={8.4} />
        <KpiCell label="Utilization" value={fmtPct(perf.kpis.utilization)} delta={2.1} />
        <KpiCell label="Client NPS" value={perf.kpis.nps} delta={4.0} />
        <KpiCell label="Retention" value={fmtPct(perf.kpis.retention)} delta={1.2} />
      </div>

      <Card title="MRR · last 12 months" sub="From $45.2K to $78.4K. Steady compounding." pad="lg">
        <div style={{ width: '100%', height: 280 }}>
          <IRC.ResponsiveContainer>
            <IRC.LineChart data={perf.mrrTrend} margin={{ top: 6, right: 12, left: 0, bottom: 0 }}>
              <IRC.CartesianGrid stroke={I_SOFT_RULE} vertical={false} />
              <IRC.XAxis dataKey="m" stroke={I_SOFT_RULE} tickLine={false} axisLine={false} />
              <IRC.YAxis stroke={I_SOFT_RULE} tickLine={false} axisLine={false} tickFormatter={(v) => '$' + (v / 1000).toFixed(0) + 'K'} />
              <IRC.Tooltip formatter={(v) => fmtMoney(v)} cursor={{ stroke: I_SOFT_RULE, strokeWidth: 1 }} />
              <IRC.Line dataKey="mrr" stroke={I_BRAND_RED} strokeWidth={2} dot={{ r: 3, fill: I_BRAND_RED }} activeDot={{ r: 5 }} />
            </IRC.LineChart>
          </IRC.ResponsiveContainer>
        </div>
      </Card>

      <Card title="Hours by client · this month" sub="Allocation. Two clients running hot." pad="lg">
        <div style={{ width: '100%', height: 280 }}>
          <IRC.ResponsiveContainer>
            <IRC.BarChart data={perf.hoursByClient} margin={{ top: 6, right: 12, left: 0, bottom: 0 }}>
              <IRC.CartesianGrid stroke={I_SOFT_RULE} vertical={false} />
              <IRC.XAxis dataKey="client" stroke={I_SOFT_RULE} tickLine={false} axisLine={false}
                tick={{ fontSize: 10 }} interval={0} angle={-20} textAnchor="end" height={60} />
              <IRC.YAxis stroke={I_SOFT_RULE} tickLine={false} axisLine={false} />
              <IRC.Tooltip cursor={{ fill: 'rgba(26,25,25,0.04)' }} />
              <IRC.Bar dataKey="hours" fill={I_RICH_BLACK}>
                {perf.hoursByClient.map((d, i) => (
                  <IRC.Cell key={i} fill={d.hours > 120 ? I_BRAND_RED : I_RICH_BLACK} />
                ))}
              </IRC.Bar>
            </IRC.BarChart>
          </IRC.ResponsiveContainer>
        </div>
      </Card>
    </div>
  );
}
window.RcgPerformanceTab = RcgPerformanceTab;

// ── CLIENT ROSTER ────────────────────────────────────────
function ClientRosterTab({ onSelectClient }) {
  const roster = window.RCG_ROSTER;
  return (
    <div className="tab-content" style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
      <TabHeader
        title="Client Roster"
        desc="Eight clients. Status, MRR, account lead, and last touch."
        right={<Pill variant="outline" size="sm"><Icon name="Plus" size={11} style={{ marginRight: 6 }} /> Add Client</Pill>}
      />

      <div className="roster-grid">
        {roster.map((c) => {
          const realClient = window.RCG_CLIENTS.find((x) => x.id === c.id);
          return (
            <div key={c.id} className="roster-card" onClick={() => realClient && onSelectClient(c.id)}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                <div className="roster-name">{c.name}</div>
                <StatusChip status={c.status} />
              </div>
              <div className="roster-meta">
                <div className="k"><span>Industry</span><b>{c.industry}</b></div>
                <div className="k"><span>MRR</span><b className="tnum">{fmtMoney(c.mrr)}</b></div>
                <div className="k"><span>Account lead</span><b>{c.accountLead}</b></div>
                <div className="k"><span>Last meeting</span><b>{c.lastMeeting}</b></div>
              </div>
              <div style={{ borderTop: '1px solid var(--border)', paddingTop: 10, marginTop: 4 }}>
                <button className="tlink" style={{ fontSize: 11.5, color: realClient ? I_BRAND_RED : 'var(--ink-stone)', borderBottomColor: realClient ? I_BRAND_RED : 'transparent', cursor: realClient ? 'pointer' : 'default' }}>
                  {realClient ? 'View dashboard →' : 'Onboarding in progress'}
                </button>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}
window.ClientRosterTab = ClientRosterTab;

// ── CONNECT SOURCES (overlay screen) ─────────────────────
function ConnectSourcesScreen({ onClose, pushToast }) {
  const [sources, setSources] = iuState(window.RCG_SOURCES);
  const [connecting, setConnecting] = iuState(null); // { id, name, phase: 'spinner'|'success' }

  function startConnect(s) {
    setConnecting({ id: s.id, name: s.name, phase: 'spinner' });
    setTimeout(() => {
      setConnecting({ id: s.id, name: s.name, phase: 'success' });
      setTimeout(() => {
        setSources((arr) => arr.map((x) => x.id === s.id ? { ...x, connected: true } : x));
        setConnecting(null);
        pushToast(`${s.name} connected.`, 'success');
      }, 900);
    }, 1200);
  }

  function disconnect(s) {
    setSources((arr) => arr.map((x) => x.id === s.id ? { ...x, connected: false } : x));
    pushToast(`${s.name} disconnected.`);
  }

  return (
    <div className="modal-backdrop" onClick={onClose} style={{ alignItems: 'flex-start', overflow: 'auto', padding: '40px 24px' }}>
      <div
        className="modal"
        onClick={(e) => e.stopPropagation()}
        style={{ maxWidth: 1080, width: '100%', padding: 40, textAlign: 'left' }}
      >
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 24, marginBottom: 28 }}>
          <div>
            <p className="kicker">Data sources</p>
            <h2 style={{ fontFamily: 'var(--serif)', fontWeight: 400, fontSize: 30, textTransform: 'uppercase', letterSpacing: '-0.025em', margin: '10px 0 6px' }}>
              Connect Sources
            </h2>
            <p style={{ fontSize: 13.5, color: 'var(--ink-stone)', margin: 0, maxWidth: '52ch' }}>
              Authenticate once. We pull metrics on a fifteen-minute cadence and surface anomalies the next morning.
            </p>
          </div>
          <button className="tlink" onClick={onClose} style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
            Close <Icon name="X" size={14} />
          </button>
        </div>

        <div className="connect-grid">
          {sources.map((s) => (
            <div className="source-card" key={s.id}>
              <div className="top">
                <div className="source-icon"><Icon name={s.icon} size={18} /></div>
                <StatusChip status={s.connected ? 'connected' : 'disconnected'} />
              </div>
              <div>
                <div className="name">{s.name}</div>
                <div className="sub">{s.connected ? 'Synced 12 min ago' : 'Authentication required'}</div>
              </div>
              <div>
                {s.connected
                  ? <Pill variant="outline" size="sm" onClick={() => disconnect(s)}>Disconnect</Pill>
                  : <Pill variant="filled" size="sm" onClick={() => startConnect(s)}>Connect</Pill>
                }
              </div>
            </div>
          ))}
        </div>

        {connecting && (
          <Modal onClose={() => {}}>
            {connecting.phase === 'spinner'
              ? <React.Fragment>
                  <div className="spin" />
                  <div className="kicker" style={{ marginBottom: 6 }}>Authenticating</div>
                  <p style={{ fontSize: 14, color: 'var(--rich-black)', margin: 0 }}>Redirecting to {connecting.name}.</p>
                </React.Fragment>
              : <React.Fragment>
                  <div className="check-circle"><Icon name="Check" size={20} /></div>
                  <div className="kicker" style={{ marginBottom: 6, color: I_DARK_GREEN }}>Connected</div>
                  <p style={{ fontSize: 14, color: 'var(--rich-black)', margin: 0 }}>Successfully connected to {connecting.name}.</p>
                </React.Fragment>
            }
          </Modal>
        )}
      </div>
    </div>
  );
}
window.ConnectSourcesScreen = ConnectSourcesScreen;

Object.assign(window, { ProspectResearchTab, RcgPerformanceTab, ClientRosterTab, ConnectSourcesScreen });
