// Brook Consultancy — TV display (v2 pass 2)
//
// Full-screen kiosk display, polls tv-feed/ every 20s. Cycles through the
// 8 most recent approved insight lines, interleaved with static case-study
// slides + a "Talk to us" QR slide every third position.
//
// Behaviour notes (from brief):
//   - bypasses the PIN gate
//   - never shows an error message; if polling fails, keeps showing cached lines
//   - typography big and readable from across an exhibition hall

// Placeholder case-study + CTA slides. The team can edit this list directly
// in src/tv-display.jsx — or in a future pass we can move it into the Drive
// settings folder for remote updates.
const TV_STATIC_SLIDES = [
  {
    kind: 'case',
    eyebrow: 'CASE STUDY · OFSTED & SOCIAL CARE',
    headline: 'The Davin home',
    body: 'A residential care provider moved from “Requires Improvement” to “Good” inside one CQC inspection cycle — with the leadership team intact and operating in surplus.'
  },
  {
    kind: 'case',
    eyebrow: 'CASE STUDY · BUSINESS TRANSFORMATION',
    headline: 'The Akisha project',
    body: 'Operating losses turned around in two quarters through a targeted finance, governance, and systems reset — without losing a single contract or senior leader.'
  },
  {
    kind: 'case',
    eyebrow: 'CASE STUDY · SMALL BUSINESS SUPPORT',
    headline: 'The Catholic school',
    body: 'A faith-based education setting unlocked an £80k surplus and rebuilt a sustainable operating model — with the leadership team given the tools to run it themselves.'
  },
  {
    kind: 'cta',
    eyebrow: 'FREE STRATEGIC BUSINESS REVIEW',
    headline: '30 minutes. Confidential. Honest insight.',
    body: 'Scan the QR code to book your slot — leave with a tailored written one-pager before you’re back at your stand.',
    qrPlaceholder: true
  }
];

function TVDisplay() {
  const [lines, setLines] = React.useState([]);
  const [error, setError] = React.useState(null);   // silent; never rendered
  const [now, setNow] = React.useState(Date.now()); // ticks for the clock
  const [idx, setIdx] = React.useState(0);          // current slide index
  const [fadeOut, setFadeOut] = React.useState(false);
  const settings = window.loadDriveSettings ? window.loadDriveSettings() : {};
  const pollMs = (window.brookRolePollMs && window.brookRolePollMs()) || 20_000;

  // Build the interleaved playlist: every 3rd position is a static slide.
  const playlist = React.useMemo(() => {
    const out = [];
    let staticIdx = 0;
    const insights = lines.slice(0, 8);
    if (insights.length === 0) {
      // Nothing approved yet — just rotate static slides
      return TV_STATIC_SLIDES.map(s => ({ ...s }));
    }
    insights.forEach((line, i) => {
      out.push({ kind: 'insight', line });
      if ((i + 1) % 2 === 0) {
        out.push({ ...TV_STATIC_SLIDES[staticIdx % TV_STATIC_SLIDES.length] });
        staticIdx++;
      }
    });
    // Always finish with a CTA slide.
    out.push(TV_STATIC_SLIDES[TV_STATIC_SLIDES.length - 1]);
    return out;
  }, [lines]);

  // Polling loop
  React.useEffect(() => {
    let cancelled = false;
    let pollTimer = null;

    async function poll() {
      if (cancelled || document.hidden) {
        pollTimer = setTimeout(poll, pollMs);
        return;
      }
      if (!settings.clientId || !settings.sharedDriveId) {
        // Not configured — just show static slides; no error on screen.
        pollTimer = setTimeout(poll, pollMs);
        return;
      }
      try {
        // Make sure we have a token. TV mode runs unattended so we use silent
        // re-auth; if that fails, we silently keep the cached lines.
        if (!window.hasValidToken()) {
          try { await window.requestAccessToken(settings.clientId, { silent: true }); }
          catch (e) { console.warn('TV silent auth failed (keeping cached lines):', e.message); }
        }
        if (window.hasValidToken()) {
          const main = await window.findOrCreateFolder(window.BROOK_MAIN_FOLDER, settings.sharedDriveId, settings.sharedDriveId);
          const tv   = await window.findOrCreateFolder(window.BROOK_TV_FOLDER, main, settings.sharedDriveId);
          const files = await window.listTVLines(tv, settings.sharedDriveId, 8);
          // Download bodies
          const fetched = await Promise.all(files.map(f =>
            window.downloadRecord(f.id).then(d => ({ ...d, _modifiedTime: f.modifiedTime })).catch(() => null)
          ));
          const fresh = fetched.filter(Boolean).map(d => d.line).filter(Boolean);
          if (!cancelled) setLines(fresh);
        }
      } catch (e) {
        console.warn('TV poll error (silent):', e);
        if (!cancelled) setError(e);
      }
      pollTimer = setTimeout(poll, pollMs);
    }

    poll();
    return () => { cancelled = true; if (pollTimer) clearTimeout(pollTimer); };
  }, [settings.clientId, settings.sharedDriveId, pollMs]);

  // Slide rotation
  React.useEffect(() => {
    if (playlist.length === 0) return;
    const SHOW_MS = 12_000;
    const FADE_MS = 700;
    const rotate = setTimeout(() => {
      setFadeOut(true);
      setTimeout(() => {
        setIdx(i => (i + 1) % playlist.length);
        setFadeOut(false);
      }, FADE_MS);
    }, SHOW_MS);
    return () => clearTimeout(rotate);
  }, [idx, playlist.length]);

  // Clock ticker
  React.useEffect(() => {
    const id = setInterval(() => setNow(Date.now()), 30_000);
    return () => clearInterval(id);
  }, []);

  const slide = playlist[idx % playlist.length] || playlist[0];

  return (
    <div className="tv-stage">
      <div className="tv-bg-mark" aria-hidden>
        <img src="assets/brook-mark-white.png" alt="" />
      </div>

      <div className="tv-corner tv-corner-tl">
        <img src="assets/brook-mark-white.png" alt="" className="tv-corner-mark" />
        <div className="tv-corner-text">
          <div className="tv-corner-name">Brook Consultancy</div>
          <div className="tv-corner-sub">Partners Ltd</div>
        </div>
      </div>

      <div className="tv-corner tv-corner-tr">
        <div className="tv-clock">
          {new Date(now).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
        </div>
      </div>

      <div className={`tv-slide${fadeOut ? ' tv-fade-out' : ' tv-fade-in'}`} key={idx}>
        {slide && slide.kind === 'insight' && <TVInsightSlide line={slide.line} />}
        {slide && slide.kind === 'case'    && <TVCaseSlide slide={slide} />}
        {slide && slide.kind === 'cta'     && <TVCtaSlide slide={slide} />}
      </div>

      <div className="tv-footer">
        <span>Three zones. Three teams. One stand. Free 30-minute strategic business reviews — book at the stand.</span>
        <span className="tv-progress">
          {playlist.map((_, i) => (
            <span key={i} className={`tv-progress-dot${i === (idx % playlist.length) ? ' active' : ''}`} />
          ))}
        </span>
      </div>
    </div>
  );
}

function TVInsightSlide({ line }) {
  return (
    <>
      <div className="tv-eyebrow tv-eyebrow-live">
        <span className="tv-live-dot" /> LIVE INSIGHT FROM TODAY’S CONVERSATIONS
      </div>
      <div className="tv-line">{line}</div>
      <div className="tv-attribution">Anonymised insight from a free strategic review at the stand · Reviewed by a Brook Consultancy partner</div>
    </>
  );
}

function TVCaseSlide({ slide }) {
  return (
    <>
      <div className="tv-eyebrow">{slide.eyebrow}</div>
      <div className="tv-headline">{slide.headline}</div>
      <div className="tv-body">{slide.body}</div>
    </>
  );
}

function TVCtaSlide({ slide }) {
  return (
    <>
      <div className="tv-eyebrow tv-eyebrow-amber">{slide.eyebrow}</div>
      <div className="tv-headline">{slide.headline}</div>
      <div className="tv-body" style={{ marginBottom: 30 }}>{slide.body}</div>
      <div className="tv-qr-block">
        <div className="tv-qr-slot">
          [QR CODE — BOOK A 30-MIN SLOT]
          <div className="tv-qr-hint">Replace with <code>assets/qr-booking.png</code> when the booking URL is final.</div>
        </div>
      </div>
    </>
  );
}

Object.assign(window, { TVDisplay, TV_STATIC_SLIDES });
