// insights-feed.jsx — dynamic Insights feed for Enginuity
//
// ─────────────────────────────────────────────────────────────────────────────
// HOW TO PUBLISH AN INSIGHT (no developer, no redeploy of the site)
// ─────────────────────────────────────────────────────────────────────────────
// The Insights section (home page + /insights) reads a JSON manifest that lists
// every insight, case study and news item. To publish something new you only
// edit that manifest — optionally dropping the linked PDF and a cover image
// next to it. The website picks it up automatically on next load.
//
// WHERE THE MANIFEST LIVES
// Set INSIGHTS_FEED_URL below. Right now it points at a file shipped with the
// site (insights/insights.json) so everything works today. When the Synology
// server is ready, change this ONE line to the server URL, e.g.:
//
//     const INSIGHTS_FEED_URL = 'https://files.enginuity.co.za/insights/insights.json';
//
// Requirements for the Synology (or any external) location:
//   1. Reachable over HTTPS.
//   2. Sends the CORS header `Access-Control-Allow-Origin: *` (or your domain)
//      so the browser is allowed to read it. Synology Web Station / a shared
//      File Station folder can be configured to do this.
// If the feed can't be reached for any reason, the site quietly falls back to
// the built-in list (window.INSIGHTS) so it never shows an empty section.
//
// MANIFEST FORMAT  (insights/insights.json)
//   { "insights": [ { ...item }, { ...item } ] }
// Each item:
//   id            unique string (optional — auto-generated if missing)
//   kind          "Insight" | "Case study" | "News"
//   title         headline
//   date          e.g. "March 2026"
//   blurb         short summary shown on the card
//   featuredBlurb (optional) longer summary for the large featured slot
//   image         (optional) cover image path/URL — falls back to a placeholder
//   href          (optional) link to the PDF/document — opens in a new tab
//   featured      (optional) true → shown large at the top of the Insights page
// ─────────────────────────────────────────────────────────────────────────────

const INSIGHTS_FEED_URL = 'insights/insights.json';

const _INSIGHT_TONES = ['studio', 'industrial', 'sky', 'earth', 'plant'];

function normalizeInsight(it, i) {
  return {
    id:            it.id || ('i' + (i + 1)),
    kind:          it.kind || 'Insight',
    title:         it.title || 'Untitled',
    date:          it.date || '',
    blurb:         it.blurb || '',
    featuredBlurb: it.featuredBlurb || it.excerpt || it.blurb || '',
    tone:          it.tone || _INSIGHT_TONES[i % _INSIGHT_TONES.length],
    image:         it.image || it.img || null,
    href:          it.href || it.url || it.document || null,
    featured:      !!it.featured,
  };
}

// React hook: returns { items, loading, error }. Starts from the built-in list,
// then swaps in the live feed once it loads.
function useInsights() {
  const fallback = (window.INSIGHTS || []).map(normalizeInsight);
  const [state, setState] = React.useState({ items: fallback, loading: true, error: null });

  React.useEffect(() => {
    let alive = true;
    if (!INSIGHTS_FEED_URL) { setState({ items: fallback, loading: false, error: null }); return; }
    fetch(INSIGHTS_FEED_URL, { cache: 'no-store' })
      .then((r) => { if (!r.ok) throw new Error('HTTP ' + r.status); return r.json(); })
      .then((data) => {
        if (!alive) return;
        const raw = Array.isArray(data) ? data : (data.insights || data.items || []);
        const items = raw.map(normalizeInsight);
        setState({ items: items.length ? items : fallback, loading: false, error: null });
      })
      .catch((err) => { if (alive) setState({ items: fallback, loading: false, error: err.message }); });
    return () => { alive = false; };
  }, []);

  return state;
}

// Shared insight card — used on the home page and the Insights index.
function InsightCard({ it, onNav }) {
  const inner = (
    <>
      <Photo aspect="4/3" tone={it.tone} src={it.image} caption={(it.title || '').slice(0, 32)} />
      <div style={{ marginTop: 18 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 12 }}>
          <span style={{
            fontFamily: '"Source Sans 3", sans-serif', fontSize: 12, fontWeight: 700,
            letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--accent)',
          }}>{it.kind}</span>
          <span style={{ fontSize: 13, color: 'var(--mid)' }}>{it.date}</span>
        </div>
        <Headline size="sm" as="h3" style={{ lineHeight: 1.25, maxWidth: '24ch' }}>{it.title}</Headline>
        {it.blurb && (
          <p style={{ margin: '12px 0 0', fontSize: 14, lineHeight: 1.55, color: 'var(--fg2)', maxWidth: '40ch' }}>
            {it.blurb}
          </p>
        )}
        {it.href && (
          <span style={{
            display: 'inline-flex', alignItems: 'center', gap: 8, marginTop: 16,
            fontFamily: '"Source Sans 3", sans-serif', fontSize: 14, fontWeight: 600,
            color: 'var(--fg)',
          }}>
            <span style={{ borderBottom: '1px solid currentColor', paddingBottom: 2 }}>Read the document</span>
            <span style={{ color: 'var(--accent)' }}>→</span>
          </span>
        )}
      </div>
    </>
  );
  const baseStyle = { cursor: 'pointer', textDecoration: 'none', color: 'inherit', display: 'block' };
  if (it.href) {
    return <a href={it.href} target="_blank" rel="noreferrer" style={baseStyle}>{inner}</a>;
  }
  return <article style={baseStyle} onClick={() => onNav && onNav('insights')}>{inner}</article>;
}

Object.assign(window, { useInsights, InsightCard, INSIGHTS_FEED_URL });
