/* ================================================================
   insights-data.jsx — Insights hub: icons, mock content, mini
   charts, the access badge, and every card variant. Exported to
   window for insights.jsx. British English; no dashes in copy.
================================================================ */
const NS = "var(--font-ui)";
const SERIF = "var(--font-serif)";

/* ---- icons ---- */
const II = {
  search: <><circle cx="11" cy="11" r="8" /><path d="m21 21-4.3-4.3" /></>,
  "chevron-down": <path d="m6 9 6 6 6-6" />,
  "arrow-right": <><path d="M5 12h14" /><path d="m12 5 7 7-7 7" /></>,
  "arrow-left": <><path d="M19 12H5" /><path d="m12 19-7-7 7-7" /></>,
  x: <><path d="M18 6 6 18" /><path d="M6 6l12 12" /></>,
  sliders: <><line x1="4" x2="4" y1="21" y2="14" /><line x1="4" x2="4" y1="10" y2="3" /><line x1="12" x2="12" y1="21" y2="12" /><line x1="12" x2="12" y1="8" y2="3" /><line x1="20" x2="20" y1="21" y2="16" /><line x1="20" x2="20" y1="12" y2="3" /><line x1="1" x2="7" y1="14" y2="14" /><line x1="9" x2="15" y1="8" y2="8" /><line x1="17" x2="23" y1="16" y2="16" /></>,
  check: <path d="M20 6 9 17l-5-5" />,
  play: <path d="M6 3v18l15-9z" fill="currentColor" stroke="none" />,
  calendar: <><rect width="18" height="18" x="3" y="4" rx="2" /><path d="M16 2v4M8 2v4M3 10h18" /></>,
  "map-pin": <><path d="M20 10c0 6-8 12-8 12s-8-6-8-12a8 8 0 0 1 16 0Z" /><circle cx="12" cy="10" r="3" /></>,
  clock: <><circle cx="12" cy="12" r="10" /><path d="M12 6v6l4 2" /></>,
  mic: <><rect width="6" height="13" x="9" y="2" rx="3" /><path d="M5 10a7 7 0 0 0 14 0M12 19v3" /></>,
  headphones: <><path d="M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H4a1 1 0 0 1-1-1v-6a9 9 0 0 1 18 0v6a1 1 0 0 1-1 1h-2a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3" /></>,
  info: <><circle cx="12" cy="12" r="10" /><path d="M12 16v-4M12 8h.01" /></>,
};
function IIcon({ name, size = 18, stroke = 2, style }) {
  return <svg style={style} width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={stroke} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">{II[name]}</svg>;
}

/* ---- taxonomy ---- */
const TYPES = ["Insight", "Publication", "Case study", "Event", "Podcast"];
const TOPICS = ["Inflation", "Monetary policy", "Commodities", "FX", "Property", "Growth", "Fiscal policy"];
const REGIONS = ["UK", "US", "Europe", "China", "Emerging markets", "Global"];
const ROLES = ["Portfolio manager", "Economist", "Strategist", "Treasury", "Risk"];
const SECTORS = ["Asset management", "Banking", "Corporate", "Government", "Professional services"];

/* ---- content (mock) ---- */
const ITEMS = [
  { id: "i1", type: "Insight", topic: "Monetary policy", region: "US", title: "The Fed's December cut still looks likely despite sticky services inflation", standfirst: "Core services printed above consensus, but our read on the path is unchanged.", author: "Paul Ashworth", date: "2026-08-12", read: 6, access: "1 credit", chart: "line", reads: 9200 },
  { id: "i2", type: "Insight", topic: "Monetary policy", region: "UK", title: "BoE holds at 4.0% but Bailey's tone turned dovish", standfirst: "We have pulled our next-cut call forward to August.", author: "Paul Dales", date: "2026-08-12", read: 4, access: "Free", chart: "bars", reads: 15400 },
  { id: "i3", type: "Publication", topic: "Growth", region: "Global", title: "Global Economic Outlook: the slow descent from higher for longer", standfirst: "Our quarterly framework for growth, inflation and policy into 2027.", author: "Jennifer McKeown", date: "2026-08-11", read: 22, access: "Subscribers", chart: "line", reads: 6100 },
  { id: "i4", type: "Insight", topic: "Commodities", region: "Global", title: "Brent at $82 is mostly risk premium; our model puts fair value near $68", standfirst: "If Middle East tensions ease, we see oil back at $68.", author: "David Oxley", date: "2026-08-11", read: 5, access: "1 credit", chart: "line", reads: 7300 },
  { id: "i5", type: "Insight", topic: "Growth", region: "China", title: "China's 5.2% Q1 GDP flatters reality; the detail is weaker", standfirst: "Property investment fell 9.8% and consumer spending is decelerating.", author: "Julian Evans-Pritchard", date: "2026-08-10", read: 7, access: "1 credit", chart: "bars", reads: 8800 },
  { id: "i6", type: "Case study", topic: "Growth", region: "UK", title: "Quantifying iwoca's impact on SME growth", standfirst: "Direct, indirect and induced impact figures for an external narrative.", author: "CE Consultancy", date: "2026-08-08", read: 9, access: "Free", chart: "bars", reads: 3400 },
  { id: "i7", type: "Insight", topic: "Inflation", region: "Europe", title: "Euro-zone disinflation is broadening beyond energy", standfirst: "Services momentum is finally rolling over on our seasonally adjusted measure.", author: "Andrew Kenningham", date: "2026-08-08", read: 5, access: "1 credit", chart: "line", reads: 5200 },
  { id: "i8", type: "Insight", topic: "FX", region: "US", title: "The dollar's rally has further to run into year-end", standfirst: "Rate differentials and safe-haven demand both point the same way.", author: "Jonas Goltermann", date: "2026-08-07", read: 4, access: "1 credit", chart: "line", reads: 6700 },
  { id: "i9", type: "Publication", topic: "Property", region: "UK", title: "UK Housing Outlook: the correction has further to run", standfirst: "Affordability and the mortgage reset keep prices soft into 2027.", author: "Ruth Gregory", date: "2026-08-06", read: 18, access: "Subscribers", chart: "bars", reads: 4100 },
  { id: "i10", type: "Insight", topic: "Fiscal policy", region: "US", title: "The US deficit is the market's real tail risk for 2027", standfirst: "Supply, not the Fed, is the story for the long end.", author: "Paul Ashworth", date: "2026-08-05", read: 6, access: "1 credit", chart: "line", reads: 5900 },
  { id: "i11", type: "Insight", topic: "Commodities", region: "Emerging markets", title: "Copper's structural bull case meets a cyclical air pocket", standfirst: "The energy-transition demand story is intact; the timing is not.", author: "Caroline Bain", date: "2026-08-05", read: 5, access: "1 credit", chart: "bars", reads: 4600 },
  { id: "i12", type: "Insight", topic: "Growth", region: "Emerging markets", title: "EM resilience is real, but it is not evenly distributed", standfirst: "We separate the balance-sheet winners from the vulnerable.", author: "William Jackson", date: "2026-08-04", read: 7, access: "Free", chart: "line", reads: 5100 },
  { id: "i13", type: "Insight", topic: "Monetary policy", region: "Europe", title: "The ECB will cut twice more before it pauses", standfirst: "The bar to a March move is lower than the market assumes.", author: "Andrew Kenningham", date: "2026-08-01", read: 4, access: "1 credit", chart: "line", reads: 4300 },
  { id: "i14", type: "Publication", topic: "Inflation", region: "Global", title: "Long Run Returns Monitor: what a higher r-star means for portfolios", standfirst: "Our updated capital-market assumptions across major asset classes.", author: "Diana Iovanel", date: "2026-07-31", read: 20, access: "Subscribers", chart: "bars", reads: 3900 },
  { id: "i15", type: "Insight", topic: "Property", region: "US", title: "US commercial real estate: the refinancing wall is smaller than feared", standfirst: "Extend-and-pretend has bought the sector more time than bears expect.", author: "Kiran Raichura", date: "2026-07-30", read: 6, access: "1 credit", chart: "bars", reads: 4700 },
  { id: "i16", type: "Insight", topic: "FX", region: "China", title: "The renminbi will weaken past 7.4 as the PBoC steps back", standfirst: "Tolerance for a softer currency is rising as growth disappoints.", author: "Julian Evans-Pritchard", date: "2026-07-29", read: 5, access: "1 credit", chart: "line", reads: 4200 },
];

const EVENTS = [
  { id: "e1", onDemand: false, format: "In person", title: "The 2027 Outlook: rates, growth and the US election aftermath", date: "2026-09-18", city: "London", venue: "Cardinal Place", topic: "Growth", region: "UK", access: "Subscribers" },
  { id: "e2", onDemand: false, format: "Online", title: "China after the stimulus: what the data is really telling us", date: "2026-09-24", topic: "Growth", region: "China", access: "Free" },
  { id: "e3", onDemand: false, format: "In person", title: "Commodities supercycle debate: our view against consensus", date: "2026-10-02", city: "Singapore", venue: "CapitaGreen", topic: "Commodities", region: "Global", access: "Subscribers" },
  { id: "e4", onDemand: false, format: "Online", title: "The dollar in 2027: how far can the rally run", date: "2026-10-09", topic: "FX", region: "US", access: "1 credit" },
  { id: "od1", onDemand: true, format: "Online", title: "Mid-year review: the higher-for-longer world", date: "2026-06-20", duration: 47, topic: "Monetary policy", region: "Global", access: "Free" },
  { id: "od2", onDemand: true, format: "Online", title: "UK inflation: the last mile", date: "2026-05-14", duration: 38, topic: "Inflation", region: "UK", access: "1 credit" },
  { id: "od3", onDemand: true, format: "In person", title: "Property markets after the reset", date: "2026-04-30", duration: 52, topic: "Property", region: "Global", access: "Subscribers" },
];

const PODCASTS = [
  { id: "p1", ep: 142, title: "The Fed blinks, and what it means for the dollar", date: "2026-08-12", duration: 26, topic: "Monetary policy", region: "US" },
  { id: "p2", ep: 141, title: "China's property drag and the global spillover", date: "2026-08-05", duration: 31, topic: "Growth", region: "China" },
  { id: "p3", ep: 140, title: "Commodities: cycle versus supercycle", date: "2026-07-29", duration: 24, topic: "Commodities", region: "Global" },
  { id: "p4", ep: 139, title: "The UK consumer is not out of the woods", date: "2026-07-22", duration: 28, topic: "Growth", region: "UK" },
];

const EXPLORE = [
  ["UK economy", "#"], ["US inflation", "#"], ["Monetary policy", "#"], ["China", "#"],
  ["Commodities", "#"], ["Property", "#"], ["FX", "#"], ["Emerging markets", "#"],
  ["Fiscal policy", "#"], ["Europe", "#"], ["Global outlook", "#"], ["Long-run returns", "#"],
];

/* ---- helpers ---- */
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
function fmtDate(iso) { const d = new Date(iso + "T00:00:00"); return d.getDate() + " " + MONTHS[d.getMonth()] + " " + d.getFullYear(); }
function dayParts(iso) { const d = new Date(iso + "T00:00:00"); return { day: d.getDate(), mon: MONTHS[d.getMonth()].toUpperCase() }; }

/* ---- mini chart thumbnail (charts signal the product) ---- */
function MiniChart({ kind = "line", seed = 1, style }) {
  const W = 320, H = 180;
  const rand = (i) => { const x = Math.sin(seed * 9301 + i * 49297) * 233280; return x - Math.floor(x); };
  if (kind === "bars") {
    const n = 9, bw = 22, gap = (W - 44 - n * bw) / (n - 1);
    return (
      <svg viewBox={`0 0 ${W} ${H}`} width="100%" height="100%" preserveAspectRatio="none" style={style} aria-hidden="true">
        {[0.33, 0.66].map((f) => <line key={f} x1="22" x2={W - 22} y1={30 + f * 120} y2={30 + f * 120} stroke="#164194" strokeOpacity="0.1" />)}
        {Array.from({ length: n }).map((_, i) => { const h = 30 + rand(i) * 110; return <rect key={i} x={22 + i * (bw + gap)} y={H - 18 - h} width={bw} height={h} rx="2" fill="#164194" fillOpacity={0.32 + (i / (n - 1)) * 0.55} />; })}
      </svg>
    );
  }
  const n = 9, pts = Array.from({ length: n }).map((_, i) => [22 + i * ((W - 44) / (n - 1)), H - 22 - rand(i) * 120]);
  const line = pts.map((p, i) => (i ? "L" : "M") + p[0].toFixed(0) + " " + p[1].toFixed(0)).join(" ");
  const area = line + ` L ${W - 22} ${H - 18} L 22 ${H - 18} Z`;
  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" height="100%" preserveAspectRatio="none" style={style} aria-hidden="true">
      <defs><linearGradient id={"mg" + seed} x1="0" y1="0" x2="0" y2="1"><stop offset="0%" stopColor="#164194" stopOpacity="0.18" /><stop offset="100%" stopColor="#164194" stopOpacity="0" /></linearGradient></defs>
      {[0.33, 0.66].map((f) => <line key={f} x1="22" x2={W - 22} y1={30 + f * 120} y2={30 + f * 120} stroke="#164194" strokeOpacity="0.1" />)}
      <path d={area} fill={`url(#mg${seed})`} />
      <path d={line} fill="none" stroke="#164194" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

/* ---- access badge ---- */
const ACCESS_TIP = {
  Free: "Free to read, no account needed.",
  "1 credit": "Costs one credit from a registered or trial account.",
  Subscribers: "Included with a full Capital Economics subscription.",
};
function AccessBadge({ level, onNavy }) {
  const cls = level === "Free" ? "is-free" : level === "1 credit" ? "is-credit" : "is-sub";
  return (
    <span className={"ins-access-wrap" + (onNavy ? " on-navy" : "")}>
      <span className={"ins-access " + cls} tabIndex={0} role="button" aria-label={"Access: " + level}>{level}</span>
      <span className="ins-tip" role="tooltip">{ACCESS_TIP[level]} <span className="ins-tip-link">Register</span></span>
    </span>
  );
}

const TYPE_BADGE = { Insight: "Insight", Publication: "Publication", "Case study": "Case study", Event: "Event", Podcast: "Podcast" };

/* ================================================================
   Cards
================================================================ */
function ArticleCard({ it, compact }) {
  const seed = parseInt(it.id.replace(/\D/g, ""), 10) || 1;
  if (compact) {
    return (
      <a href="#" className="ins-card-compact">
        <div className="ins-cc-top">
          <span className="ins-badge-type">{TYPE_BADGE[it.type]}</span>
          <AccessBadge level={it.access} />
        </div>
        <h4 className="ins-cc-title">{it.title}</h4>
        <div className="ins-meta"><span>{fmtDate(it.date)}</span></div>
      </a>
    );
  }
  return (
    <a href="#" className="ins-card">
      <div className="ins-thumb">
        <MiniChart kind={it.chart} seed={seed} style={{ display: "block" }} />
        <span className="ins-badge-type ins-badge-over">{TYPE_BADGE[it.type]}</span>
      </div>
      <div className="ins-card-body">
        <div className="ins-eyebrow">{it.topic} · {it.region}</div>
        <h3 className="ins-title">{it.title}</h3>
        {it.standfirst && <p className="ins-standfirst">{it.standfirst}</p>}
        <div className="ins-meta">
          <span>{fmtDate(it.date)}</span><span className="ins-dot">·</span><span>{it.read} min read</span>
          <span style={{ marginLeft: "auto" }}><AccessBadge level={it.access} /></span>
        </div>
      </div>
    </a>
  );
}

function LeadCard({ it }) {
  const seed = parseInt(it.id.replace(/\D/g, ""), 10) || 1;
  return (
    <a href="#" className="ins-card ins-lead">
      <div className="ins-thumb ins-thumb-lead">
        <MiniChart kind={it.chart} seed={seed} style={{ display: "block" }} />
        <span className="ins-badge-type ins-badge-over">{TYPE_BADGE[it.type]}</span>
      </div>
      <div className="ins-card-body">
        <div className="ins-eyebrow">{it.topic} · {it.region}</div>
        <h3 className="ins-title ins-title-lead">{it.title}</h3>
        {it.standfirst && <p className="ins-standfirst ins-standfirst-lead">{it.standfirst}</p>}
        <div className="ins-meta">
          <span>{it.author}</span><span className="ins-dot">·</span><span>{fmtDate(it.date)}</span>
          <span style={{ marginLeft: "auto" }}><AccessBadge level={it.access} /></span>
        </div>
      </div>
    </a>
  );
}

function EventCard({ ev }) {
  const { day, mon } = dayParts(ev.date);
  return (
    <div className="ins-event-card">
      <div className="ins-event-head">
        <div className="ins-date-block"><span className="ins-date-day">{day}</span><span className="ins-date-mon">{mon}</span></div>
        <span className={"ins-format " + (ev.format === "In person" ? "is-inperson" : "is-online")}>{ev.format}</span>
      </div>
      <h3 className="ins-event-title">{ev.title}</h3>
      <div className="ins-event-meta">
        {ev.onDemand ? (
          <span className="ins-event-line"><IIcon name="clock" size={15} />{ev.duration} min</span>
        ) : ev.format === "In person" ? (
          <span className="ins-event-line"><IIcon name="map-pin" size={15} />{ev.city}, {ev.venue}</span>
        ) : (
          <span className="ins-event-line"><IIcon name="calendar" size={15} />Live online</span>
        )}
        <AccessBadge level={ev.access} />
      </div>
      <div className="ins-event-cta">
        {ev.onDemand
          ? <button className="ins-mini-btn"><IIcon name="play" size={14} />Watch now</button>
          : <button className="ins-mini-btn ins-mini-btn-solid">Reserve a place</button>}
      </div>
    </div>
  );
}

function PodcastCard({ p }) {
  return (
    <div className="ins-pod-card">
      <div className="ins-pod-top">
        <span className="ins-pod-ep">Episode {p.ep}</span>
        <span className="ins-pod-free">Free</span>
      </div>
      <h3 className="ins-pod-title">{p.title}</h3>
      <div className="ins-pod-foot">
        <button className="ins-pod-play" aria-label="Play episode"><IIcon name="play" size={16} /></button>
        <span className="ins-pod-meta">{fmtDate(p.date)} · {p.duration} min</span>
      </div>
    </div>
  );
}

function ConversionModule() {
  return (
    <div className="ins-conv-module">
      <div className="ins-conv-eyebrow">Read more of it</div>
      <h3 className="ins-conv-h">Every card here opens on a free trial.</h3>
      <p className="ins-conv-p">Start a 7-day trial for capped, read-only access, or register for 3 credits to open individual pieces.</p>
      <div className="ins-conv-actions">
        <button className="ce-btn ce-btn-primary ins-conv-primary">Start free trial</button>
        <a href="#register" className="ins-conv-sec">Register for 3 credits</a>
      </div>
    </div>
  );
}

Object.assign(window, {
  NS_INS: NS, SERIF_INS: SERIF, IIcon, II,
  TYPES, TOPICS, REGIONS, ROLES, SECTORS,
  ITEMS, EVENTS, PODCASTS, EXPLORE,
  fmtDate, dayParts, MiniChart, AccessBadge, ArticleCard, LeadCard, EventCard, PodcastCard, ConversionModule,
});
