/* IntelliScan - synthetic open-source intelligence dossier for a person.
   ALL CONTENT IS FABRICATED demo data, generated deterministically from the
   (fictional) person's id. Renders inside the full-width Person → Overview.
   Exports: IntelliScan, ScanSpiral, isScanned.                            */

function isHash(str) { let h = 2166136261; for (let i = 0; i < str.length; i++) { h ^= str.charCodeAt(i); h = Math.imul(h, 16777619); } return h >>> 0; }
function isRng(seed) { let s = seed >>> 0; return function () { s = (s + 0x6D2B79F5) | 0; let t = Math.imul(s ^ (s >>> 15), 1 | s); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; }

function isScanned(id) { try { return localStorage.getItem("intelliscan_" + id) === "true"; } catch (e) { return false; } }

/* little blue spiral marker shown on scanned people's cards */
function ScanSpiral({ size = 15, title = "IntelliScanned" }) {
  return (
    <span title={title} style={{ display: "inline-grid", placeItems: "center", flex: "none", width: size + 5, height: size + 5, borderRadius: 999, background: "var(--accent-soft)" }}>
      <svg viewBox="0 0 24 24" width={size} height={size} fill="none" stroke="var(--accent)" strokeWidth="2.1" strokeLinecap="round">
        <path d="M12 12.2a1.6 1.6 0 1 1-1.2-1.55 a3.5 3.5 0 1 1-2.9 3.65 a5.6 5.6 0 1 1 5.3-5.95 a7.8 7.8 0 1 1-7.9 7.6" />
      </svg>
    </span>
  );
}

const IS_LOCATIONS = ["London", "Manchester", "Bristol", "Edinburgh", "Leeds", "Cambridge", "Oxford", "Brighton", "Glasgow", "Sheffield"];
const IS_MOODS = [["Positive", "var(--good)"], ["Reflective", "var(--info)"], ["Energised", "var(--accent)"], ["Focused", "var(--accent)"], ["Calm", "var(--good)"], ["Upbeat", "var(--good)"], ["Measured", "var(--warn)"]];
const IS_SECTOR = {
  education: { topics: ["literacy", "ed-tech", "school reform", "youth opportunity"], verb: "championing classroom innovation" },
  arts: { topics: ["theatre", "cultural funding", "live performance", "creative access"], verb: "advocating for the arts" },
  science: { topics: ["open science", "research integrity", "data infrastructure", "fellowships"], verb: "advancing open research" },
  health: { topics: ["mental health", "community care", "wellbeing", "access to therapy"], verb: "expanding care access" },
  civic: { topics: ["local democracy", "community power", "civic tech", "participation"], verb: "building civic capacity" },
  media: { topics: ["press freedom", "investigative journalism", "media literacy", "public interest"], verb: "defending independent media" },
  philanthropy: { topics: ["grant-making", "impact measurement", "philanthropy", "systems change"], verb: "deploying catalytic capital" },
};
const IS_SOURCES = ["Public social profiles", "X / Twitter activity", "Instagram media", "Facebook posts", "News & press mentions", "Event appearances", "Location signals", "Sentiment & mood model", "Network graph", "Personality inference"];

function buildIntel(person) {
  const D = window.DATA;
  const org = person.org ? D.byId[person.org] : null;
  const domain = org ? org.domain : "philanthropy";
  const sector = IS_SECTOR[domain] || IS_SECTOR.philanthropy;
  const rnd = isRng(isHash(person.id + person.name));
  const pick = (arr) => arr[Math.floor(rnd() * arr.length)];
  const pickN = (arr, n) => { const c = [...arr], o = []; while (o.length < n && c.length) o.push(c.splice(Math.floor(rnd() * c.length), 1)[0]); return o; };
  const int = (a, b) => a + Math.floor(rnd() * (b - a + 1));
  const handleBase = person.name.toLowerCase().replace(/[^a-z]/g, "");
  const first = person.name.split(" ")[0];

  const scores = { sentiment: int(58, 92), influence: int(40, 95), reach: int(30, 88), openness: int(45, 90), risk: int(8, 42), authenticity: int(70, 98) };
  const followers = int(800, 48000);
  const topics = sector.topics;
  const home = pick(IS_LOCATIONS);
  const mood = pick(IS_MOODS);

  const xPosts = [
    { text: `Huge week ${sector.verb}. The momentum behind ${topics[0]} right now is genuinely energising. 🙌`, t: int(2, 9) + "h", likes: int(40, 900), reposts: int(5, 120) },
    { text: `Grateful to everyone who showed up for the ${pick(topics)} roundtable in ${home}. Real progress when the right people are in the room.`, t: int(1, 4) + "d", likes: int(20, 400), reposts: int(2, 60) },
    { text: `Reading everything I can on ${pick(topics)} this month. If you've got a paper or thread I should see, send it my way.`, t: int(4, 9) + "d", likes: int(15, 220), reposts: int(1, 30) },
  ];
  const igCaps = [
    { c: `Morning light over ${home}.`, mood: "Calm", loc: home },
    { c: `Behind the scenes at today's ${pick(topics)} session.`, mood: "Focused", loc: home },
    { c: `Team offsite 🌿 grateful for these people.`, mood: "Positive", loc: pick(IS_LOCATIONS) },
    { c: `Field visit - seeing the work up close.`, mood: "Reflective", loc: pick(IS_LOCATIONS) },
    { c: `Coffee & strategy ☕`, mood: "Energised", loc: home },
    { c: `Weekend reset. Back at it Monday.`, mood: "Upbeat", loc: home },
  ];
  const igPhotos = igCaps.map((x, i) => ({ ...x, seed: isHash(person.id + "ig" + i) % 1000, likes: int(60, 1200) }));
  const fbPosts = [
    { text: `Proud to share that our ${pick(topics)} work was featured this week. Years of effort from an incredible team.`, t: int(1, 3) + "d", reactions: int(30, 300) },
    { text: `Looking forward to speaking at the upcoming convening on ${pick(topics)}. If you'll be there, let's connect.`, t: int(4, 11) + "d", reactions: int(15, 160) },
  ];
  const liPosts = [
    { text: `Reflections on ${pick(topics)}: the sector moves faster when funders and practitioners share what's working. Thread below 👇`, t: int(1, 6) + "d", reactions: int(50, 700) },
    { text: `We're hiring across our ${pick(topics)} programme - please share with anyone brilliant.`, t: int(7, 16) + "d", reactions: int(20, 240) },
  ];

  const locations = pickN(IS_LOCATIONS, 4).map((p, i) => ({ place: p, when: ["Today", "2 days ago", "Last week", "2 weeks ago"][i], ctx: pick(["Conference", "Office", "Site visit", "Speaking", "Meeting", "Travel"]) }));
  const moodTrend = Array.from({ length: 8 }, () => int(45, 95));
  const affinities = pickN(topics, Math.min(4, topics.length)).map((t) => ({ label: t, pct: int(55, 96) }));
  const footprint = [
    { plat: "x", handle: "@" + handleBase, followers, active: "Daily" },
    { plat: "instagram", handle: "@" + handleBase + "_", followers: Math.round(followers * 0.6), active: "Weekly" },
    { plat: "facebook", handle: person.name, followers: Math.round(followers * 0.4), active: "Occasional" },
    { plat: "linkedin", handle: person.name, followers: Math.round(followers * 1.3), active: "Weekly" },
  ];
  const photoAnalysis = { mood: mood[0], moodColor: mood[1], setting: pick(["Conference stage", "Office / co-working", "Outdoor / urban", "Panel discussion", "Community venue"]), activity: pick(["Public speaking", "Networking", "Team collaboration", "Site visit", "Travel"]), location: home, people: int(1, 12), confidence: int(82, 97) };

  // NEW intel
  const personality = [
    { label: "Openness", pct: int(55, 96) }, { label: "Conscientiousness", pct: int(55, 95) },
    { label: "Extraversion", pct: int(35, 92) }, { label: "Agreeableness", pct: int(50, 94) }, { label: "Drive", pct: int(55, 97) },
  ];
  const commStyle = pick(["Warm & relational", "Direct & concise", "Analytical & evidence-led", "Visionary & big-picture", "Collaborative & consensus-seeking"]);
  const decisionDriver = pick(["Impact evidence", "Peer endorsement", "Mission alignment", "Long-term relationship", "Speed & momentum"]);

  // associates from real ecosystem data where possible
  const assoc = [];
  const seen = new Set([person.id]);
  if (org && org.account && org.account !== person.id && D.byId[org.account]) { assoc.push({ id: org.account, name: D.byId[org.account].name, rel: "Account holder", strength: int(70, 95) }); seen.add(org.account); }
  (org ? D.people.filter((p) => p.org === org.id && !seen.has(p.id)) : D.people.filter((p) => p.team && !seen.has(p.id))).forEach((p) => { if (assoc.length < 3) { assoc.push({ id: p.id, name: p.name, rel: "Colleague", strength: int(55, 88) }); seen.add(p.id); } });
  if (org) (org.linked || []).map((l) => D.byId[l]).filter(Boolean).forEach((lo) => { if (lo.contact && D.byId[lo.contact] && !seen.has(lo.contact) && assoc.length < 5) { assoc.push({ id: lo.contact, name: D.byId[lo.contact].name, rel: "Via " + lo.name, strength: int(40, 75) }); seen.add(lo.contact); } });
  while (assoc.length < 4) { const nm = pick(["Rachel Adeyemi", "Tom Brennan", "Priya Shah", "Olu Martins", "Hannah Cole", "Sam Reyes"]); if (!assoc.find((a) => a.name === nm)) assoc.push({ name: nm, rel: "Inferred contact", strength: int(35, 60) }); }

  const NEWS_SRC = ["The Guardian", "Third Sector", "Civil Society", "BBC", "Local Press", "Sector Weekly"];
  const news = [
    { headline: `${org ? org.name : "Foundation"} backs new ${topics[0]} drive`, src: pick(NEWS_SRC), when: int(2, 5) + "d ago", sent: "Positive" },
    { headline: `${first} joins panel on the future of ${pick(topics)}`, src: pick(NEWS_SRC), when: int(1, 3) + "w ago", sent: "Neutral" },
    { headline: `Comment: why ${pick(topics)} needs patient funding`, src: pick(NEWS_SRC), when: int(1, 2) + "mo ago", sent: "Positive" },
  ];
  const engage = { bestDay: pick(["Tuesday", "Wednesday", "Thursday"]), bestTime: pick(["early morning", "mid-morning", "lunchtime", "late afternoon"]), channel: pick(["Email", "LinkedIn DM", "Warm intro", "Event"]), approach: pick(["Lead with impact evidence", "Open with a shared connection", "Invite to a relevant convening", "Offer a peer introduction"]), responseRate: int(45, 88) };
  const interests = [...new Set([...topics, ...pickN(["running", "photography", "live music", "books", "cycling", "cooking", "travel"], 2)])];

  const summary = `${person.name} is an actively engaged ${org ? `figure in the ${(D.domains.find((d) => d.id === domain) || {}).label || "sector"}` : "philanthropy professional"}, ${sector.verb} with a consistent public voice across ${footprint.length} platforms. Footprint reads ${scores.authenticity}% authentic with a predominantly ${mood[0].toLowerCase()} tone; sentiment is trending ${moodTrend[7] >= moodTrend[0] ? "upward" : "steady"}. Communication style is ${commStyle.toLowerCase()}, and decisions appear driven by ${decisionDriver.toLowerCase()}. Influence is ${scores.influence >= 70 ? "high" : scores.influence >= 50 ? "moderate" : "emerging"} within ${topics[0]} circles, most active around ${home}. No reputational risk signals of note (risk index ${scores.risk}/100). Best reached ${engage.bestDay} ${engage.bestTime} via ${engage.channel.toLowerCase()} - ${engage.approach.toLowerCase()}.`;

  return { domain, scores, followers, topics, home, xPosts, igPhotos, fbPosts, liPosts, locations, moodTrend, affinities, footprint, photoAnalysis, summary, handleBase, personality, commStyle, decisionDriver, assoc, news, engage, interests };
}

/* brand glyphs (generic monograms, not official logos) */
function BrandGlyph({ plat, size = 26 }) {
  const st = { width: size, height: size, flex: "none", borderRadius: plat === "x" ? 7 : size * 0.32, display: "grid", placeItems: "center", color: "#fff", fontWeight: 800, fontSize: size * 0.5 };
  if (plat === "x") return <span style={{ ...st, background: "#0a0a0a" }}>𝕏</span>;
  if (plat === "facebook") return <span style={{ ...st, background: "#1877f2", fontFamily: "Georgia, serif" }}>f</span>;
  if (plat === "instagram") return <span style={{ ...st, background: "linear-gradient(135deg,#feda75,#d62976 45%,#962fbf 80%,#4f5bd5)" }}><Icon name="user" size={size * 0.52} /></span>;
  if (plat === "linkedin") return <span style={{ ...st, background: "#0a66c2", fontSize: size * 0.42 }}>in</span>;
  return <span style={st}>?</span>;
}

function ISPhoto({ p }) {
  const [err, setErr] = React.useState(false);
  const url = `https://picsum.photos/seed/is${p.seed}/400/400`;
  return (
    <div style={{ position: "relative", aspectRatio: "1", borderRadius: 12, overflow: "hidden", background: "var(--surface-3)" }}>
      {!err ? <img src={url} alt="" onError={() => setErr(true)} style={{ width: "100%", height: "100%", objectFit: "cover", display: "block", filter: "saturate(0.95)" }} />
        : <div style={{ width: "100%", height: "100%", background: "linear-gradient(135deg,var(--surface-3),var(--surface-2))" }} />}
      <div style={{ position: "absolute", inset: 0, background: "linear-gradient(180deg, transparent 45%, rgba(10,12,18,0.78))" }} />
      <div style={{ position: "absolute", top: 8, left: 8 }}><span style={{ fontSize: 9.5, fontWeight: 700, color: "#fff", background: "rgba(0,0,0,0.5)", padding: "3px 7px", borderRadius: 999 }}>AI · {p.mood}</span></div>
      <div style={{ position: "absolute", left: 9, right: 9, bottom: 8 }}>
        <div style={{ fontSize: 10.5, color: "#fff", fontWeight: 550, lineHeight: 1.3, textShadow: "0 1px 3px rgba(0,0,0,.5)", overflow: "hidden", display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical" }}>{p.c}</div>
        <div style={{ fontSize: 9, color: "rgba(255,255,255,0.8)", marginTop: 2, display: "flex", alignItems: "center", gap: 4 }}><Icon name="map" size={9} /> {p.loc} · ♥ {p.likes}</div>
      </div>
    </div>
  );
}

/* shared section card */
function ISCard({ title, icon, glyph, right, children, style, tone }) {
  const toned = tone ? { background: tone === "good" ? "var(--good-bg)" : "var(--accent-soft)", borderColor: "transparent" } : {};
  const tc = tone === "good" ? "var(--good)" : "var(--accent)";
  return (
    <div className="card" style={{ padding: 18, display: "flex", flexDirection: "column", height: "100%", ...toned, ...style }}>
      <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 14 }}>
        {glyph || (icon && <Icon name={icon} size={16} style={{ color: tone ? tc : "var(--text-muted)" }} />)}
        <div style={{ fontWeight: 650, fontSize: 14.5, color: tone ? tc : "var(--text)" }}>{title}</div>
        {right && <div style={{ marginLeft: "auto" }}>{right}</div>}
      </div>
      {children}
    </div>
  );
}

function PostList({ posts, plat, name, handle, metric }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 11 }}>
      {posts.map((p, i) => (
        <div key={i} style={{ display: "flex", gap: 11, padding: "12px 13px", border: "1px solid var(--border)", borderRadius: 12, background: "var(--surface-2)" }}>
          <BrandGlyph plat={plat} size={32} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
              <span style={{ fontSize: 12.5, fontWeight: 700 }}>{name}</span>
              <span style={{ fontSize: 11.5, color: "var(--text-faint)" }}>{handle ? handle + " · " : ""}{p.t}</span>
            </div>
            <div style={{ fontSize: 13, lineHeight: 1.5, marginTop: 3 }}>{p.text}</div>
            <div style={{ marginTop: 8, fontSize: 11.5, color: "var(--text-faint)" }}>{metric(p)}</div>
          </div>
        </div>
      ))}
    </div>
  );
}

function IntelliScan({ person, onOpen }) {
  const D = window.DATA;
  const [done, setDone] = useLocalState("intelliscan_" + person.id, false);
  const [scanning, setScanning] = React.useState(false);
  const [step, setStep] = React.useState(0);
  const [social, setSocial] = React.useState("x");
  const data = React.useMemo(() => buildIntel(person), [person.id]);

  const run = () => {
    setScanning(true); setStep(0);
    let i = 0;
    const iv = setInterval(() => { i++; setStep(i); if (i >= IS_SOURCES.length) { clearInterval(iv); setTimeout(() => { setScanning(false); setDone(true); }, 450); } }, 320);
  };

  if (!done && !scanning) {
    return (
      <div className="card" style={{ padding: 0, overflow: "hidden", position: "relative" }}>
        <div style={{ position: "absolute", inset: 0, background: "radial-gradient(120% 130% at 85% 0%, var(--accent-soft-2), transparent 60%)", pointerEvents: "none" }} />
        <div style={{ position: "relative", padding: "30px 28px", display: "flex", alignItems: "center", gap: 24, flexWrap: "wrap" }}>
          <div style={{ flex: 1, minWidth: 280 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 10 }}>
              <span style={{ width: 30, height: 30, borderRadius: 9, display: "grid", placeItems: "center", background: "var(--accent)", color: "var(--accent-contrast)" }}><Icon name="target" size={16} /></span>
              <span className="t-eyebrow" style={{ color: "var(--accent)" }}>NeuroAI · Intelligence screening</span>
            </div>
            <div className="display" style={{ fontSize: 24, marginBottom: 8 }}>Run an IntelliScan on {person.name.split(" ")[0]}</div>
            <div style={{ fontSize: 14, color: "var(--text-muted)", lineHeight: 1.6, maxWidth: 560 }}>NeuroAI sweeps public sources - social profiles, posts, photos, press and location signals - then profiles personality, mood, influence and the best way to engage.</div>
            <div style={{ display: "flex", gap: 7, flexWrap: "wrap", marginTop: 16 }}>
              {IS_SOURCES.slice(0, 6).map((s) => <span key={s} className="badge" style={{ background: "var(--surface-2)" }}>{s}</span>)}
              <span className="badge" style={{ background: "var(--surface-2)" }}>+4 more</span>
            </div>
          </div>
          <button className="btn btn-primary" onClick={run} style={{ fontSize: 15, padding: "13px 22px" }}><Icon name="target" size={17} /> Run IntelliScan</button>
        </div>
      </div>
    );
  }

  if (scanning) {
    return (
      <div className="card" style={{ padding: "34px 30px" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 22 }}>
          <span className="is-pulse" style={{ width: 38, height: 38, borderRadius: 11, display: "grid", placeItems: "center", background: "var(--accent)", color: "var(--accent-contrast)" }}><Icon name="target" size={20} /></span>
          <div><div style={{ fontSize: 17, fontWeight: 700 }}>Scanning {person.name}…</div><div style={{ fontSize: 13, color: "var(--text-muted)" }}>NeuroAI is correlating public intelligence sources</div></div>
          <span className="mono" style={{ marginLeft: "auto", fontSize: 22, fontWeight: 700, color: "var(--accent)" }}>{Math.round((step / IS_SOURCES.length) * 100)}%</span>
        </div>
        <div style={{ height: 8, borderRadius: 5, background: "var(--surface-3)", overflow: "hidden", marginBottom: 22 }}><div style={{ width: (step / IS_SOURCES.length * 100) + "%", height: "100%", background: "var(--accent)", borderRadius: 5, transition: "width .3s ease" }} /></div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "9px 24px" }}>
          {IS_SOURCES.map((s, i) => {
            const state = i < step ? "done" : i === step ? "active" : "wait";
            return (
              <div key={s} style={{ display: "flex", alignItems: "center", gap: 11, opacity: state === "wait" ? 0.4 : 1, transition: ".2s" }}>
                <span style={{ width: 20, height: 20, flex: "none", borderRadius: 999, display: "grid", placeItems: "center", background: state === "done" ? "var(--good)" : state === "active" ? "var(--accent)" : "var(--surface-3)", color: "#fff" }}>{state === "done" ? <Icon name="check" size={12} /> : state === "active" ? <span className="is-pulse" style={{ width: 7, height: 7, borderRadius: 999, background: "#fff" }} /> : null}</span>
                <span style={{ fontSize: 13, fontWeight: state === "active" ? 600 : 450, color: state === "wait" ? "var(--text-muted)" : "var(--text)" }}>{s}</span>
              </div>
            );
          })}
        </div>
      </div>
    );
  }

  const sc = data.scores;
  const maxMood = Math.max(...data.moodTrend);
  const ScoreDot = ({ label, val, color, invert }) => {
    const c = invert ? (val < 20 ? "var(--good)" : val < 40 ? "var(--warn)" : "var(--rose)") : (color || "var(--accent)");
    return (
      <div style={{ flex: 1, minWidth: 96 }}>
        <div className="mono" style={{ fontSize: 22, fontWeight: 700, color: c, lineHeight: 1 }}>{val}<span style={{ fontSize: 12, color: "var(--text-faint)" }}>/100</span></div>
        <div style={{ fontSize: 11.5, color: "var(--text-muted)", marginTop: 4 }}>{label}</div>
        <div style={{ height: 4, borderRadius: 3, background: "var(--surface-3)", overflow: "hidden", marginTop: 6 }}><div style={{ width: val + "%", height: "100%", background: c, borderRadius: 3 }} /></div>
      </div>
    );
  };
  const SOCIAL_TABS = [{ id: "x", label: "X", plat: "x" }, { id: "instagram", label: "Instagram", plat: "instagram" }, { id: "facebook", label: "Facebook", plat: "facebook" }, { id: "linkedin", label: "LinkedIn", plat: "linkedin" }];

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
      {/* header */}
      <div className="card" style={{ padding: "16px 20px", display: "flex", alignItems: "center", gap: 13, flexWrap: "wrap" }}>
        <span style={{ width: 34, height: 34, flex: "none", borderRadius: 10, display: "grid", placeItems: "center", background: "var(--accent)", color: "var(--accent-contrast)" }}><Icon name="target" size={18} /></span>
        <div style={{ flex: 1, minWidth: 180 }}>
          <div style={{ fontSize: 15.5, fontWeight: 700 }}>IntelliScan dossier</div>
          <div style={{ fontSize: 12.5, color: "var(--text-muted)" }}>Synthesised by NeuroAI from {data.footprint.length} platforms + public signals · just now</div>
        </div>
        <span className="badge" style={{ background: "var(--good-bg)", color: "var(--good)", borderColor: "transparent" }}><Icon name="check" size={12} /> Scan complete</span>
        <button className="btn btn-sm" onClick={() => setDone(false)}><Icon name="recenter" size={14} /> Re-scan</button>
      </div>

      <AINote title="Executive profile">{data.summary}</AINote>

      {/* score strip */}
      <div className="card" style={{ padding: 18 }}>
        <div style={{ display: "flex", gap: 18, flexWrap: "wrap" }}>
          <ScoreDot label="Sentiment" val={sc.sentiment} color="var(--good)" />
          <ScoreDot label="Influence" val={sc.influence} color="var(--accent)" />
          <ScoreDot label="Reach" val={sc.reach} color="var(--info)" />
          <ScoreDot label="Openness to engage" val={sc.openness} color="var(--accent)" />
          <ScoreDot label="Authenticity" val={sc.authenticity} color="var(--good)" />
          <ScoreDot label="Risk index" val={sc.risk} invert />
        </div>
      </div>

      {/* main: social (tabbed) + side intel */}
      <div style={{ display: "grid", gridTemplateColumns: "1.55fr 1fr", gap: 14, alignItems: "stretch" }}>
        {/* unified social intelligence */}
        <div className="card" style={{ padding: 0, overflow: "hidden", display: "flex", flexDirection: "column" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 9, padding: "15px 18px 0" }}>
            <Icon name="signal" size={16} style={{ color: "var(--text-muted)" }} />
            <div style={{ fontWeight: 650, fontSize: 14.5 }}>Social intelligence</div>
            <span className="badge" style={{ marginLeft: "auto", background: "var(--accent-soft)", color: "var(--accent)", borderColor: "transparent" }}><Icon name="spark" size={11} /> aggregated</span>
          </div>
          <div style={{ display: "flex", gap: 2, padding: "12px 14px 0", borderBottom: "1px solid var(--border)" }}>
            {SOCIAL_TABS.map((t) => {
              const on = social === t.id;
              return <button key={t.id} className="focusable" onClick={() => setSocial(t.id)} style={{ display: "inline-flex", alignItems: "center", gap: 7, font: "inherit", fontSize: 12.5, fontWeight: 600, cursor: "pointer", padding: "8px 12px", border: "none", borderBottom: "2px solid " + (on ? "var(--accent)" : "transparent"), background: "none", color: on ? "var(--text)" : "var(--text-muted)", marginBottom: -1 }}>
                <BrandGlyph plat={t.plat} size={18} /> {t.label}
              </button>;
            })}
          </div>
          <div style={{ padding: 16, flex: 1 }}>
            {social === "x" && <PostList posts={data.xPosts} plat="x" name={person.name} handle={"@" + data.handleBase} metric={(p) => `♻ ${p.reposts}   ♥ ${p.likes}`} />}
            {social === "facebook" && <PostList posts={data.fbPosts} plat="facebook" name={person.name} handle="" metric={(p) => `👍❤️ ${p.reactions} reactions`} />}
            {social === "linkedin" && <PostList posts={data.liPosts} plat="linkedin" name={person.name} handle="" metric={(p) => `💬 ${p.reactions} reactions`} />}
            {social === "instagram" && (
              <div>
                <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 9, marginBottom: 14 }}>
                  {data.igPhotos.map((p, i) => <ISPhoto key={i} p={p} />)}
                </div>
                <div style={{ padding: "13px 15px", borderRadius: 12, background: "var(--surface-2)", border: "1px solid var(--border)" }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 7, marginBottom: 10 }}><Icon name="spark" size={13} style={{ color: "var(--accent)" }} /><span className="t-eyebrow">AI vision · latest photo</span></div>
                  <div style={{ display: "flex", flexWrap: "wrap", gap: 18 }}>
                    {[["Mood", data.photoAnalysis.mood, data.photoAnalysis.moodColor], ["Setting", data.photoAnalysis.setting], ["Activity", data.photoAnalysis.activity], ["Location", data.photoAnalysis.location], ["People", String(data.photoAnalysis.people)], ["Confidence", data.photoAnalysis.confidence + "%"]].map(([k, v, c]) => (
                      <div key={k}><div style={{ fontSize: 10.5, color: "var(--text-faint)", textTransform: "uppercase", letterSpacing: "0.04em" }}>{k}</div><div style={{ fontSize: 13, fontWeight: 600, color: c || "var(--text)" }}>{v}</div></div>
                    ))}
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>

        {/* side intel column */}
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <ISCard title="Digital footprint" icon="link">
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              {data.footprint.map((f) => (
                <div key={f.plat} style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 10px", border: "1px solid var(--border)", borderRadius: 10, background: "var(--surface-2)" }}>
                  <BrandGlyph plat={f.plat} size={26} />
                  <div style={{ flex: 1, minWidth: 0 }}><div style={{ fontSize: 12.5, fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{f.handle}</div><div style={{ fontSize: 11, color: "var(--text-faint)" }}>{f.followers.toLocaleString("en-GB")} followers · {f.active}</div></div>
                </div>
              ))}
            </div>
          </ISCard>
          <ISCard title="News & press mentions" icon="document" right={<span className="badge mono">{data.news.length}</span>} style={{ flex: 1 }}>
            <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
              {data.news.map((n, i) => (
                <div key={i} style={{ paddingBottom: 9, borderBottom: i < data.news.length - 1 ? "1px solid var(--border)" : "none" }}>
                  <div style={{ fontSize: 12.5, fontWeight: 550, lineHeight: 1.4 }}>{n.headline}</div>
                  <div style={{ fontSize: 11, color: "var(--text-faint)", marginTop: 3, display: "flex", alignItems: "center", gap: 7 }}>{n.src} · {n.when} <span className="badge" style={{ background: n.sent === "Positive" ? "var(--good-bg)" : "var(--surface-2)", color: n.sent === "Positive" ? "var(--good)" : "var(--text-muted)", borderColor: "transparent", padding: "1px 7px" }}>{n.sent}</span></div>
                </div>
              ))}
            </div>
          </ISCard>
        </div>
      </div>

      {/* intel row: personality / associates / engagement */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 14, alignItems: "stretch" }}>
        <ISCard title="Personality profile" icon="user">
          <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
            {data.personality.map((t) => (
              <div key={t.label}>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, marginBottom: 4 }}><span>{t.label}</span><span className="mono" style={{ color: "var(--text-muted)" }}>{t.pct}</span></div>
                <div style={{ height: 5, borderRadius: 3, background: "var(--surface-3)", overflow: "hidden" }}><div style={{ width: t.pct + "%", height: "100%", background: "var(--accent)", borderRadius: 3 }} /></div>
              </div>
            ))}
          </div>
          <div style={{ marginTop: 12, paddingTop: 12, borderTop: "1px solid var(--border)", display: "flex", flexDirection: "column", gap: 6 }}>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12 }}><span style={{ color: "var(--text-muted)" }}>Comms style</span><span style={{ fontWeight: 600 }}>{data.commStyle}</span></div>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12 }}><span style={{ color: "var(--text-muted)" }}>Decision driver</span><span style={{ fontWeight: 600 }}>{data.decisionDriver}</span></div>
          </div>
        </ISCard>

        <ISCard title="Known associates" icon="directory" right={<span className="badge mono">{data.assoc.length}</span>}>
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {data.assoc.map((a, i) => (
              <button key={i} className="focusable" onClick={() => a.id && onOpen(a.id)} style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 10px", border: "1px solid var(--border)", borderRadius: 10, background: "var(--surface-2)", cursor: a.id ? "pointer" : "default", textAlign: "left" }}>
                <Avatar name={a.name} size={30} accent={!!a.id} />
                <div style={{ flex: 1, minWidth: 0 }}><div style={{ fontSize: 12.5, fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{a.name}</div><div style={{ fontSize: 11, color: "var(--text-faint)" }}>{a.rel}</div></div>
                <span className="mono" style={{ fontSize: 10.5, color: "var(--text-muted)" }}>{a.strength}%</span>
              </button>
            ))}
          </div>
        </ISCard>

        <ISCard title="Engagement playbook" icon="spark" tone="good">
          <div style={{ display: "flex", flexDirection: "column", gap: 9, flex: 1, justifyContent: "center" }}>
            {[["Best day", data.engage.bestDay], ["Best time", data.engage.bestTime], ["Channel", data.engage.channel], ["Approach", data.engage.approach]].map(([k, v]) => (
              <div key={k} style={{ display: "flex", justifyContent: "space-between", gap: 10, fontSize: 12.5, paddingBottom: 8, borderBottom: "1px solid color-mix(in srgb, var(--good) 22%, transparent)" }}>
                <span style={{ color: "var(--text-muted)", flex: "none" }}>{k}</span><span style={{ fontWeight: 600, textAlign: "right" }}>{v}</span>
              </div>
            ))}
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 2 }}>
              <span style={{ fontSize: 12.5, color: "var(--text-muted)" }}>Response likelihood</span>
              <div style={{ flex: 1, height: 6, borderRadius: 3, background: "color-mix(in srgb, var(--good) 22%, transparent)", overflow: "hidden" }}><div style={{ width: data.engage.responseRate + "%", height: "100%", background: "var(--good)", borderRadius: 3 }} /></div>
              <span className="mono" style={{ fontSize: 12, fontWeight: 700, color: "var(--good)" }}>{data.engage.responseRate}%</span>
            </div>
          </div>
        </ISCard>
      </div>

      {/* mood / location / topics */}
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 14, alignItems: "stretch" }}>
        <ISCard title="Mood & sentiment" icon="trendingUp">
          <div style={{ display: "flex", alignItems: "flex-end", gap: 5, height: 76, marginBottom: 8 }}>
            {data.moodTrend.map((v, i) => <div key={i} style={{ flex: 1, height: (v / maxMood * 100) + "%", background: v >= 70 ? "var(--good)" : v >= 50 ? "var(--accent)" : "var(--warn)", borderRadius: "4px 4px 0 0", minHeight: 4 }} title={v + "/100"} />)}
          </div>
          <div style={{ fontSize: 12, color: "var(--text-muted)" }}>8-week trend · {data.moodTrend[7] >= data.moodTrend[0] ? <span style={{ color: "var(--good)" }}>up ↑</span> : <span style={{ color: "var(--warn)" }}>steady →</span>}</div>
        </ISCard>
        <ISCard title="Location signals" icon="map">
          <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
            {data.locations.map((l, i) => (
              <div key={i} style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <span style={{ width: 26, height: 26, flex: "none", borderRadius: 8, display: "grid", placeItems: "center", background: i === 0 ? "var(--accent-soft)" : "var(--surface-3)", color: i === 0 ? "var(--accent)" : "var(--text-muted)" }}><Icon name="map" size={13} /></span>
                <div style={{ flex: 1, minWidth: 0 }}><div style={{ fontSize: 12.5, fontWeight: 600 }}>{l.place}</div><div style={{ fontSize: 11, color: "var(--text-faint)" }}>{l.ctx}</div></div>
                <span style={{ fontSize: 11, color: "var(--text-muted)" }}>{l.when}</span>
              </div>
            ))}
          </div>
        </ISCard>
        <ISCard title="Topics & interests" icon="spark">
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {data.affinities.map((a) => (
              <div key={a.label}>
                <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, marginBottom: 4 }}><span style={{ textTransform: "capitalize" }}>{a.label}</span><span className="mono" style={{ color: "var(--text-muted)" }}>{a.pct}%</span></div>
                <div style={{ height: 5, borderRadius: 3, background: "var(--surface-3)", overflow: "hidden" }}><div style={{ width: a.pct + "%", height: "100%", background: "var(--accent)", borderRadius: 3 }} /></div>
              </div>
            ))}
            <div style={{ display: "flex", flexWrap: "wrap", gap: 5, marginTop: 4 }}>{data.interests.map((t) => <span key={t} className="badge" style={{ background: "var(--surface-2)", textTransform: "capitalize" }}>{t}</span>)}</div>
          </div>
        </ISCard>
      </div>

      <div style={{ fontSize: 11, color: "var(--text-faint)", textAlign: "center", padding: "2px 0 0" }}>IntelliScan generates an illustrative profile from synthetic demo data. No real personal data is collected.</div>
    </div>
  );
}

window.IntelliScan = IntelliScan;
window.ScanSpiral = ScanSpiral;
window.isScanned = isScanned;
