/* Wh4 — shared components used across pages:
   social links, cookie banner, current-mandate cards/conveyor, news cards.
   Content comes from site-config.js (window.WH4_CONFIG) and
   content.js (window.WH4_CONTENT). */

const { useState: useStateS, useEffect: useEffectS } = React;

function fmtWh4S(str) {
  const parts = String(str).split(/Wh4/);
  if (parts.length === 1) return str;
  return parts.flatMap((p, i) => i === 0 ? [p] : [<React.Fragment key={i}>Wh<sup>4</sup></React.Fragment>, p]);
}

const WH4_EMAIL = 'hello@wh4.co.uk';

/* ---------- Social links ---------- */
const SOCIAL_NETWORKS = [
  { key: 'linkedin', label: 'LinkedIn', icon: (
    <svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor" aria-hidden="true"><path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433a2.062 2.062 0 1 1 0-4.125 2.062 2.062 0 0 1 0 4.125zM7.119 20.452H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z"/></svg>
  ) },
  { key: 'x', label: 'X', icon: (
    <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor" aria-hidden="true"><path d="M18.901 1.153h3.68l-8.04 9.19L24 22.846h-7.406l-5.8-7.584-6.638 7.584H.474l8.6-9.83L0 1.154h7.594l5.243 6.932ZM17.61 20.644h2.039L6.486 3.24H4.298Z"/></svg>
  ) },
  { key: 'instagram', label: 'Instagram', icon: (
    <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden="true"><rect x="3" y="3" width="18" height="18" rx="5"/><circle cx="12" cy="12" r="4"/><circle cx="17.5" cy="6.5" r="1" fill="currentColor" stroke="none"/></svg>
  ) },
  { key: 'youtube', label: 'YouTube', icon: (
    <svg viewBox="0 0 24 24" width="18" height="18" fill="currentColor" aria-hidden="true"><path d="M23.498 6.186a3.016 3.016 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 0 0 .502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 0 0 2.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 0 0 2.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814zM9.545 15.568V8.432L15.818 12l-6.273 3.568z"/></svg>
  ) },
];

function SocialLinks({ className = '' }) {
  const urls = (window.WH4_CONFIG && window.WH4_CONFIG.social) || {};
  const items = SOCIAL_NETWORKS.filter((n) => urls[n.key]);
  if (!items.length) return null;
  return (
    <div className={'social-links ' + className}>
      {items.map((n) => (
        <a key={n.key} href={urls[n.key]} target="_blank" rel="noopener noreferrer" aria-label={'Wh4 on ' + n.label} title={n.label}>
          {n.icon}
        </a>
      ))}
    </div>
  );
}

/* ---------- Cookie banner (consent for Google Analytics) ---------- */
function CookieBanner() {
  const consent = window.wh4Consent;
  const [show, setShow] = useStateS(() => (consent ? consent.needsChoice() : false));
  useEffectS(() => {
    const open = () => setShow(true);
    window.addEventListener('wh4:cookie-settings', open);
    return () => window.removeEventListener('wh4:cookie-settings', open);
  }, []);
  if (!show || !consent) return null;
  const choose = (v) => { consent.set(v); setShow(false); };

  if (!consent.analyticsAvailable) {
    return (
      <div className="cookie-notice" role="dialog" aria-label="Cookie notice">
        <p>We use essential cookies and similar browser storage to make this site work. See our <a href="cookies.html">Cookie Policy</a>.</p>
        <button onClick={() => choose('ack')}>OK</button>
      </div>
    );
  }
  return (
    <div className="cookie-notice cookie-notice--choice" role="dialog" aria-label="Cookie preferences">
      <p>We use essential storage to make this site work and, with your consent, Google Analytics to understand how it is used. See our <a href="cookies.html">Cookie Policy</a>.</p>
      <div className="cookie-actions">
        <button className="cookie-btn-secondary" onClick={() => choose('essential')}>Essential only</button>
        <button onClick={() => choose('all')}>Accept analytics</button>
      </div>
    </div>
  );
}

function CookieSettingsLink({ children = 'Cookie settings' }) {
  return (
    <a href="cookies.html" onClick={(e) => { if (window.wh4Consent) { e.preventDefault(); window.wh4Consent.open(); } }}>{children}</a>
  );
}

/* ---------- Current mandates — M&A "tombstones" ---------- */
function getMandates() {
  return ((window.WH4_CONTENT && window.WH4_CONTENT.mandates) || []).filter(Boolean);
}

function mandateMailto(m) {
  const subject = 'Mandate enquiry: ' + m.codename;
  const body = 'Hello Wh4 team,\n\nI would like to receive further information on ' + m.codename + ' (' + m.sector + ').\n\nName:\nCompany:\nPhone:\n';
  return 'mailto:' + WH4_EMAIL + '?subject=' + encodeURIComponent(subject) + '&body=' + encodeURIComponent(body);
}

function ArrowIcon({ size = 14 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" aria-hidden="true">
      <path d="M5 12h14M13 5l7 7-7 7" />
    </svg>
  );
}

function MandateCard({ m, index = 0, hidden }) {
  const status = (m.status || 'Live').trim();
  const statusCls = status.toLowerCase().replace(/\s+/g, '-');
  return (
    <a
      className="tomb"
      href={mandateMailto(m)}
      aria-hidden={hidden ? 'true' : undefined}
      tabIndex={hidden ? -1 : undefined}
    >
      <div className="tomb-inner">
        <div className="tomb-top">
          <span className="tomb-no">No. {String(index + 1).padStart(2, '0')}</span>
          <span className={'tomb-status is-' + statusCls}>{status}</span>
        </div>
        <div className="tomb-main">
          <div className="tomb-sector">{m.sector}</div>
          <h3 className="tomb-name">{fmtWh4S(m.codename)}</h3>
          {m.summary && <p className="tomb-summary">{m.summary}</p>}
        </div>
        <dl className="tomb-facts">
          {m.location && <div><dt>Location</dt><dd>{m.location}</dd></div>}
          {m.metric && <div><dt>Indicative size</dt><dd>{m.metric}</dd></div>}
        </dl>
        <div className="tomb-foot">
          <em>Sell-side adviser</em>
          <span className="tomb-cta">Enquire <ArrowIcon size={13} /></span>
        </div>
      </div>
    </a>
  );
}

/* Infinite, slow-moving row of tombstones. Pauses on hover/focus; becomes a
   swipeable row for visitors who prefer reduced motion. */
function MandatesConveyor() {
  const list = getMandates();
  if (!list.length) return null;
  let loop = list.map((m, i) => ({ m, i }));
  while (loop.length < 6) loop = loop.concat(list.map((m, i) => ({ m, i })));
  const hasSample = list.some((m) => m.sample);
  return (
    <div className="mandates-block">
      <div className="mandate-conveyor" style={{ '--conveyor-dur': (loop.length * 9) + 's' }}>
        <div className="mandate-track">
          {loop.map((x, k) => <MandateCard m={x.m} index={x.i} key={'a' + k} hidden={k >= list.length} />)}
          {loop.map((x, k) => <MandateCard m={x.m} index={x.i} key={'b' + k} hidden />)}
        </div>
      </div>
      <div className="mandates-foot">
        <a href="mandates.html" className="text-link">View all current mandates <ArrowIcon /></a>
        {hasSample && <p className="sample-note">Illustrative mandates shown for review.</p>}
      </div>
    </div>
  );
}

/* ---------- News — editorial list ---------- */
function getNews() {
  const list = ((window.WH4_CONTENT && window.WH4_CONTENT.news) || []).filter(Boolean);
  return list.slice().sort((a, b) => String(b.date).localeCompare(String(a.date)));
}

function formatNewsDate(iso, style = 'long') {
  const d = new Date(iso + 'T12:00:00');
  if (isNaN(d)) return iso || '';
  if (style === 'short') {
    const m = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][d.getMonth()];
    return d.getDate() + ' ' + m + ' ' + d.getFullYear();
  }
  return d.toLocaleDateString('en-GB', { day: 'numeric', month: 'long', year: 'numeric' });
}

function newsHref(n) {
  return n.url ? n.url : 'news.html?post=' + encodeURIComponent(n.slug);
}

function NewsRow({ n }) {
  const external = !!n.url;
  return (
    <a className="news-row" href={newsHref(n)} {...(external ? { target: '_blank', rel: 'noopener noreferrer' } : {})}>
      <time className="news-row-date" dateTime={n.date}>{formatNewsDate(n.date, 'short')}</time>
      <span className="news-row-cat">{n.category}</span>
      <div className="news-row-main">
        <h3 className="news-row-title">{fmtWh4S(n.title)}</h3>
        {n.excerpt && <p className="news-row-excerpt">{fmtWh4S(n.excerpt)}</p>}
      </div>
      <span className="news-row-go" aria-hidden="true"><ArrowIcon size={16} /></span>
    </a>
  );
}

function NewsList({ items }) {
  return <div className="news-list">{items.map((n) => <NewsRow n={n} key={n.slug} />)}</div>;
}

/* Homepage section — three latest items */
function NewsStrip() {
  const list = getNews().slice(0, 3);
  if (!list.length) return null;
  const hasSample = list.some((n) => n.sample);
  return (
    <section className="news-strip" id="news">
      <div className="container">
        <div className="news-strip-head">
          <div>
            <p className="eng-kicker">News &amp; insights</p>
            <h2 className="news-strip-title">Latest from Wh<sup>4</sup>.</h2>
          </div>
          <a href="news.html" className="text-link">All news <ArrowIcon /></a>
        </div>
        <NewsList items={list} />
        {hasSample && <p className="sample-note">Draft articles shown for review.</p>}
      </div>
    </section>
  );
}

Object.assign(window, {
  fmtWh4S, SocialLinks, CookieBanner, CookieSettingsLink, ArrowIcon,
  getMandates, mandateMailto, MandateCard, MandatesConveyor,
  getNews, formatNewsDate, newsHref, NewsRow, NewsList, NewsStrip,
});
