'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';

interface TickerItem {
  id: string;
  href: string;
  title: string;
  category?: string | null;
  author_name?: string | null;
  kind?: 'thread' | 'reply';
}

const REFRESH_MS = 5 * 60 * 1000;

async function fetchItems(url: string): Promise<TickerItem[]> {
  try {
    const res = await fetch(url, { cache: 'no-store' });
    if (!res.ok) return [];
    const d = await res.json();
    return Array.isArray(d.items) ? d.items : [];
  } catch {
    return [];
  }
}

function Row({
  label,
  labelColor,
  glowColor,
  durationSec,
  items,
}: {
  label: string;
  labelColor: string;
  glowColor: string;
  durationSec: number;
  items: TickerItem[];
}) {
  // Duplicate the items so the strip loops seamlessly. Animation moves
  // the inner track from 0 to -50% (the duplicated half), then snaps
  // back to 0 — invisible thanks to the duplication.
  const safe = items.length > 0 ? items : [{ id: 'empty', href: '#', title: '—' }];
  const looped = [...safe, ...safe];

  return (
    <div
      className="bbt-row"
      style={{
        // height + bg/border baked into class; per-row dynamic values here
        ['--bbt-duration' as any]: `${durationSec}s`,
        ['--bbt-label-color' as any]: labelColor,
        ['--bbt-glow-color' as any]: glowColor,
      }}
    >
      <span className="bbt-label" aria-hidden="true">
        {label}
      </span>
      <div className="bbt-track-wrapper">
        <div className="bbt-track">
          {looped.map((item, idx) => (
            <Link
              key={`${item.id}-${idx}`}
              href={item.href}
              className="bbt-item"
              prefetch={false}
            >
              {item.category && (
                <span className="bbt-cat">{item.category}</span>
              )}
              <span className="bbt-title">{item.title}</span>
              {item.author_name && (
                <span className="bbt-meta">· {item.author_name}</span>
              )}
              <span className="bbt-sep" aria-hidden="true">•</span>
            </Link>
          ))}
        </div>
      </div>
    </div>
  );
}

export default function DualSpeedTicker() {
  const [beat, setBeat] = useState<TickerItem[]>([]);
  const [forum, setForum] = useState<TickerItem[]>([]);

  useEffect(() => {
    let cancelled = false;
    const tick = async () => {
      const [b, f] = await Promise.all([
        fetchItems('/api/ticker/beat-news'),
        fetchItems('/api/ticker/forum-posts'),
      ]);
      if (!cancelled) {
        setBeat(b);
        setForum(f);
      }
    };
    tick();
    const handle = setInterval(tick, REFRESH_MS);
    return () => {
      cancelled = true;
      clearInterval(handle);
    };
  }, []);

  return (
    <div className="max-w-container mx-auto px-4">
    <aside className="bbt-root" aria-label="News + forum live ticker">
      <Row
        label="INDUSTRY NEWS"
        labelColor="#ff4035"
        glowColor="rgba(0,255,159,0.55)"
        durationSec={228}
        items={beat}
      />
      <Row
        label="RECENT FORUM POSTS"
        labelColor="#1D4ED8"
        glowColor="rgba(0,212,255,0.55)"
        durationSec={206}
        items={forum}
      />

      {/* Scoped styles. Plain CSS keyframes = GPU-accelerated, no JS-frame
          overhead, no flicker. */}
      <style>{`
        .bbt-root {
          background: #000;
          border: 1px solid rgba(0,255,159,0.18);
          border-bottom-color: rgba(0,212,255,0.18);
          font-family: ui-monospace, "JetBrains Mono", "SF Mono", Menlo, Consolas, monospace;
          color: #d1d5db;
        }
        .bbt-row {
          position: relative;
          display: flex;
          align-items: center;
          height: 28px;
          overflow: hidden;
          contain: layout paint;
        }
        .bbt-row + .bbt-row {
          border-top: 1px solid rgba(255,255,255,0.05);
        }
        .bbt-label {
          flex-shrink: 0;
          height: 100%;
          display: inline-flex;
          align-items: center;
          padding: 0 12px;
          font-size: 10px;
          letter-spacing: 0.22em;
          font-weight: 700;
          color: var(--bbt-label-color);
          text-shadow: 0 0 6px var(--bbt-glow-color);
          background: linear-gradient(90deg, rgba(0,0,0,1) 0%, rgba(0,0,0,0.85) 100%);
          border-right: 1px solid var(--bbt-label-color);
          box-shadow: inset 0 0 12px var(--bbt-glow-color);
          z-index: 2;
        }
        .bbt-track-wrapper {
          flex: 1;
          position: relative;
          overflow: hidden;
          height: 100%;
        }
        .bbt-track {
          display: inline-flex;
          align-items: center;
          height: 100%;
          white-space: nowrap;
          animation: bbt-scroll var(--bbt-duration) linear infinite;
          will-change: transform;
        }
        .bbt-row:hover .bbt-track {
          animation-play-state: paused;
        }
        .bbt-item {
          display: inline-flex;
          align-items: center;
          gap: 6px;
          padding: 0 14px;
          height: 100%;
          font-size: 12px;
          color: #d1d5db;
          text-decoration: none;
          transition: color 120ms ease;
        }
        .bbt-item:hover .bbt-title {
          color: var(--bbt-label-color);
          text-shadow: 0 0 6px var(--bbt-glow-color);
        }
        .bbt-cat {
          font-size: 9px;
          letter-spacing: 0.18em;
          text-transform: uppercase;
          color: var(--bbt-label-color);
          opacity: 0.85;
        }
        .bbt-title {
          font-weight: 500;
        }
        .bbt-meta {
          color: #6b7280;
          font-size: 11px;
        }
        .bbt-sep {
          color: var(--bbt-label-color);
          opacity: 0.4;
          margin-left: 10px;
        }
        @keyframes bbt-scroll {
          0%   { transform: translateX(0); }
          100% { transform: translateX(-50%); }
        }
        @media (max-width: 640px) {
          .bbt-label { font-size: 9px; padding: 0 8px; }
          .bbt-item { font-size: 11px; padding: 0 10px; }
        }
      `}</style>
    </aside>
    </div>
  );
}
