// News: data layer, the News page (list + single article).
//
// Stories live in content/news.json, edited by club officials through Pages
// CMS (config in .pages.yml). Every save commits to GitHub and Vercel
// redeploys, so this file never needs touching to add a story.
//
// Each story: title, date (YYYY-MM-DD), category?, summary, body?, image?,
// image_alt?, facts? [{label, value}], button_label?, button_link?, home_until?
// ---------------------------------------------------------------------------

const NEWS_URL = 'content/news.json';
const HOME_DAYS = 30; // with no home_until, a story stays on the home page this long

const todayIso = () => {
  const t = new Date();
  return `${t.getFullYear()}-${String(t.getMonth() + 1).padStart(2, '0')}-${String(t.getDate()).padStart(2, '0')}`;
};

const addDaysIso = (iso, days) => {
  const d = new Date(iso + 'T12:00:00');
  d.setDate(d.getDate() + days);
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
};

const slugify = (s) => String(s || '').toLowerCase()
  .replace(/&/g, ' and ').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60);

// Pages CMS may store dates with a time part; keep just the day.
const isoDay = (v) => String(v || '').slice(0, 10);

const normaliseStory = (raw) => {
  const date = isoDay(raw.date);
  const facts = Array.isArray(raw.facts) ? raw.facts.filter(f => f && (f.label || f.value)) : [];
  return {
    ...raw,
    date,
    home_until: isoDay(raw.home_until),
    facts,
    slug: `${date}-${slugify(raw.title)}`,
  };
};

const formatNewsDate = (iso) => {
  if (!iso) return '';
  const d = new Date(iso + 'T12:00:00');
  if (isNaN(d)) return iso;
  return d.toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric' });
};

const onHomePage = (s, today) => {
  if (!s.date || s.date > today) return false;
  const until = s.home_until || addDaysIso(s.date, HOME_DAYS);
  return today <= until;
};

// One fetch per page load, shared by every component that asks.
let _newsPromise = null;
const loadNews = () => {
  if (!_newsPromise) {
    _newsPromise = fetch(NEWS_URL, { cache: 'no-cache' })
      .then(r => r.ok ? r.json() : Promise.reject(new Error('HTTP ' + r.status)))
      .then(list => (Array.isArray(list) ? list : [])
        .filter(s => s && s.title)
        .map(normaliseStory)
        .filter(s => s.date && s.date <= todayIso()) // future-dated stories wait until their day
        .sort((a, b) => (a.date < b.date ? 1 : a.date > b.date ? -1 : 0)))
      .catch(() => []);
  }
  return _newsPromise;
};

const useNews = () => {
  const [news, setNews] = React.useState(null);
  React.useEffect(() => {
    let alive = true;
    loadNews().then(list => { if (alive) setNews(list); });
    return () => { alive = false; };
  }, []);
  return news; // null while loading
};

const openStory = (slug) => {
  window.dispatchEvent(new CustomEvent('wren:navigate', { detail: { page: 'news', story: slug || null } }));
};

// Body text: blank line = new paragraph, single line break kept.
const StoryBody = ({ text }) => {
  const paras = String(text || '').split(/\n\s*\n/).map(p => p.trim()).filter(Boolean);
  return (
    <div className="story__body">
      {paras.map((p, i) => (
        <p key={i}>{p.split('\n').map((line, k) => <React.Fragment key={k}>{k > 0 && <br />}{line}</React.Fragment>)}</p>
      ))}
    </div>
  );
};

const NewsCard = ({ s }) => (
  <a className="newsCard" href={'#news/' + s.slug} onClick={(e) => { e.preventDefault(); openStory(s.slug); }}>
    <div className="newsCard__img">
      {s.image
        ? <img src={s.image} alt={s.image_alt || ''} loading="lazy" decoding="async" />
        : <div className="newsCard__placeholder"><img src="assets/logo.jpg" alt="" /></div>}
    </div>
    <div className="newsCard__copy">
      <div className="mono newsCard__meta">
        {formatNewsDate(s.date)}{s.category ? ' · ' + s.category : ''}
      </div>
      <h3 className="display newsCard__title">{s.title}</h3>
      {s.summary && <p className="newsCard__summary">{s.summary}</p>}
      <span className="mono newsCard__more">Read more →</span>
    </div>
  </a>
);

const NewsList = ({ news }) => {
  if (news === null) return <p className="newsEmpty">Loading news…</p>;
  if (!news.length) return <p className="newsEmpty">No news yet. Check back soon, or follow the club on Facebook for live updates.</p>;
  return (
    <div className="newsGrid">
      {news.map(s => <NewsCard key={s.slug} s={s} />)}
    </div>
  );
};

const StoryView = ({ s, news }) => {
  const others = (news || []).filter(o => o.slug !== s.slug).slice(0, 3);
  return (
    <article className="story">
      <a className="mono story__back" href="#news" onClick={(e) => { e.preventDefault(); openStory(null); }}>← All news</a>
      <div className="mono story__meta">
        {formatNewsDate(s.date)}{s.category ? ' · ' + s.category : ''}
      </div>
      <h2 className="display story__title">{s.title}</h2>
      {s.summary && <p className="story__lede">{s.summary}</p>}
      {s.image && (
        <figure className="story__figure">
          <img src={s.image} alt={s.image_alt || ''} decoding="async" />
        </figure>
      )}
      {s.body && <StoryBody text={s.body} />}
      {s.facts.length > 0 && (
        <dl className="story__facts">
          {s.facts.map((f, i) => (
            <div key={i}><dt className="mono">{f.label}</dt><dd>{f.value}</dd></div>
          ))}
        </dl>
      )}
      {s.button_link && (
        <div style={{ marginTop: 28 }}>
          <Btn variant="primary" size="md" as="a" href={s.button_link} target="_blank" rel="noopener noreferrer">
            {s.button_label || 'Find out more'}
          </Btn>
        </div>
      )}
      {others.length > 0 && (
        <div className="story__more">
          <SectionHead kicker="Club News" title="More stories" />
          <div className="newsGrid">
            {others.map(o => <NewsCard key={o.slug} s={o} />)}
          </div>
        </div>
      )}
    </article>
  );
};

const NewsPage = ({ story }) => {
  const news = useNews();
  const current = story && news ? news.find(s => s.slug === story) : null;
  return (
    <section style={{ background: 'var(--paper)', padding: '64px 0 96px' }}>
      <div className="container">
        {story && news && !current && (
          <p className="newsEmpty">That story could not be found. It may have been removed.</p>
        )}
        {current
          ? <StoryView s={current} news={news} />
          : <NewsList news={news} />}
      </div>
    </section>
  );
};

Object.assign(window, { useNews, onHomePage, todayIso, formatNewsDate, openStory, NewsPage });
