// ============================================================
// Components — data-driven; all content comes from /api/data
// ============================================================

const { useState, useEffect, useRef, useCallback } = React;

// ─────────────────────────────────────────────────────
// Profile Header
// ─────────────────────────────────────────────────────
function ProfileHeader({ profile }) {
  const [copied, setCopied] = useState(false);

  const copyMail = () => {
    navigator.clipboard?.writeText(profile.email);
    setCopied(true);
    setTimeout(() => setCopied(false), 1600);
  };

  return (
    <header className="profile">
      <div className={`avatar-wrap ${profile.isLive ? "is-live" : ""}`}>
        <div className="avatar-ring" aria-hidden="true"></div>
        <img src={profile.avatar} alt={profile.handle} className="avatar-img" />
        {profile.isLive && (
          <span className="live-badge">
            <span className="live-dot"></span>
            LIVE
          </span>
        )}
      </div>

      <h1 className="handle">
        <span className="handle-glow" data-edit-key="profile_name">{profile.handle}</span>
      </h1>
      <p className="alias" data-edit-key="profile_alias">{profile.alias}</p>
      <p className="tagline" data-edit-key="profile_tagline">{profile.tagline}</p>

      {profile.email && (
        <button className={`mail-pill ${copied ? "copied" : ""}`} onClick={copyMail}>
          <Icon name="mail" />
          <span className="mail-text">{copied ? "kopiert!" : profile.email}</span>
          <Icon name="copy" className="mail-copy" />
        </button>
      )}
    </header>
  );
}

// ─────────────────────────────────────────────────────
// Live-Now Card (visible only when live)
// ─────────────────────────────────────────────────────
function LiveCard({ profile }) {
  if (!profile.isLive) return null;
  return (
    <a href={profile.twitchUrl || '#'} className="live-card" target="_blank" rel="noopener noreferrer">
      <div className="live-card-left">
        <span className="live-dot lg"></span>
        <div>
          <div className="live-card-eyebrow">Stream läuft gerade</div>
          <div className="live-card-title">{profile.liveTitle}</div>
        </div>
      </div>
      <div className="live-card-right">
        <Icon name="viewers" />
        <span>{profile.liveViewers}</span>
        <Icon name="arrow" className="live-card-go" />
      </div>
    </a>
  );
}

// ─────────────────────────────────────────────────────
// Stats Strip
// ─────────────────────────────────────────────────────
function StatsStrip({ stats }) {
  return (
    <div className="stats">
      {stats.map((s) => (
        <div className="stat" key={s.id}>
          <Icon name={s.platform} className="stat-icon" />
          <div className="stat-value">{s.value}</div>
          <div className="stat-label">{s.label}</div>
        </div>
      ))}
    </div>
  );
}

// ─────────────────────────────────────────────────────
// Link Tile
// ─────────────────────────────────────────────────────
function LinkTile({ link }) {
  return (
    <a href={link.href} className={`link-tile ${link.variant === "primary" ? "is-primary" : ""}`} target="_blank" rel="noopener noreferrer" data-link-id={link.id}>
      <span className="link-icon"><Icon name={link.icon} /></span>
      <span className="link-body">
        <span className="link-label">{link.label}</span>
        {link.sub && <span className="link-sub">{link.sub}</span>}
      </span>
      <span className="link-arrow"><Icon name="arrow" /></span>
    </a>
  );
}

function LinksGrid({ links }) {
  const primary = links.filter((l) => l.variant === "primary");
  const rest = links.filter((l) => l.variant !== "primary");
  return (
    <section className="links">
      {primary.map((l) => <LinkTile key={l.id} link={l} />)}
      <div className="links-grid">
        {rest.map((l) => <LinkTile key={l.id} link={l} />)}
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────────────
// VibeCheck — "Arbeitszeitbetrug" Status
// ─────────────────────────────────────────────────────
function VibeCheck({ vibe: initialVibe }) {
  const pool = window.VIBE_POOL;
  const pick = (arr) => arr[Math.floor(Math.random() * arr.length)];

  const [vibe, setVibe] = useState(initialVibe);
  const [shake, setShake] = useState(false);

  const reroll = useCallback(() => {
    if (!pool) return;
    setVibe({
      status:       pick(pool.status),
      mood:         pick(pool.mood),
      lastStream:   pick(pool.lastStream),
      nextMaybe:    pick(pool.next),
      streamChance: Math.floor(Math.random() * 88) + 8,
      coffees:      Math.floor(Math.random() * 6) + 1,
    });
    setShake(true);
    setTimeout(() => setShake(false), 400);
  }, [pool]);

  useEffect(() => {
    if (!pool) return;
    reroll();
    const t = setInterval(reroll, 20 * 60 * 1000);
    return () => clearInterval(t);
  }, [reroll, pool]);

  return (
    <section className="vibe">
      <div className="section-head">
        <h2 className="section-title">
          <span className="schedule-icon-wrap"><Icon name="cherry" /></span>
          Vibe Check
        </h2>
        <button className="section-link vibe-reroll" onClick={reroll}>
          Arbeitszeitbetrug™ live · reroll
        </button>
      </div>

      <div className={`vibe-card ${shake ? "is-rolling" : ""}`}>
        <div className="vibe-row vibe-row-status">
          <span className="vibe-eyebrow">macht gerade</span>
          <span key={vibe.status} className="vibe-status">"{vibe.status}"</span>
        </div>

        <div className="vibe-meter">
          <div className="vibe-meter-head">
            <span className="vibe-eyebrow">Stream-Wahrscheinlichkeit heute</span>
            <span className="vibe-meter-pct">{vibe.streamChance}%</span>
          </div>
          <div className="vibe-meter-track">
            <div className="vibe-meter-fill" style={{ width: `${vibe.streamChance}%` }}>
              <span className="vibe-meter-glow"></span>
            </div>
          </div>
          <div className="vibe-meter-foot">
            <span>kein Bock</span>
            <span>maybe</span>
            <span>ON GOD</span>
          </div>
        </div>

        <div className="vibe-grid">
          <div className="vibe-cell">
            <div className="vibe-cell-label">Mood</div>
            <div key={vibe.mood} className="vibe-cell-value">{vibe.mood}</div>
          </div>
          <div className="vibe-cell">
            <div className="vibe-cell-label">Last Stream</div>
            <div key={vibe.lastStream} className="vibe-cell-value">{vibe.lastStream}</div>
          </div>
          <div className="vibe-cell">
            <div className="vibe-cell-label">Redbulls heute</div>
            <div key={vibe.coffees} className="vibe-cell-value">{"⚡".repeat(Math.min(vibe.coffees, 5))}</div>
          </div>
        </div>

        <div className="vibe-footer">
          <span className="vibe-eyebrow">nächster stream</span>
          <span key={vibe.nextMaybe} className="vibe-next">{vibe.nextMaybe}</span>
        </div>

        <div className="vibe-disclaimer">
          <span className="vibe-disclaimer-tag">/jk</span>
          <span>alles automatisch erfunden · refresh alle 20 min · Frau Kirsche selbst weiß auch nicht was sie tut</span>
        </div>
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────────────
// Featured Video — YouTube embed or uploaded file
// ─────────────────────────────────────────────────────
function VideoSection({ video }) {
  if (!video) return null;

  let embedSrc = null;
  if (video.type === 'youtube') {
    const m = video.url.match(/(?:v=|youtu\.be\/|embed\/)([a-zA-Z0-9_-]{11})/);
    if (m) embedSrc = `https://www.youtube.com/embed/${m[1]}?rel=0`;
  }

  return (
    <section className="video-section">
      <div className="video-wrap">
        {video.type === 'youtube' && embedSrc ? (
          <iframe
            src={embedSrc}
            title="Featured Video"
            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
            allowFullScreen
            frameBorder="0"
          />
        ) : video.type === 'upload' ? (
          <video src={video.url} controls playsInline />
        ) : null}
      </div>
    </section>
  );
}

// ─────────────────────────────────────────────────────
// Reels — supports both real thumbnails and CSS gradients
// ─────────────────────────────────────────────────────
function ReelCard({ reel }) {
  // Real thumb: starts with / (local upload) or https (external)
  const hasRealThumb = reel.thumb && (reel.thumb.startsWith('/') || reel.thumb.startsWith('http'));

  return (
    <a href={reel.href || '#'} className="reel" data-thumb={reel.thumb} data-reel-id={reel.id} target="_blank" rel="noopener noreferrer">
      <div className="reel-thumb">
        {hasRealThumb ? (
          <img
            src={reel.thumb}
            alt={reel.title}
            style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', objectPosition: 'center', display: 'block' }}
            onError={e => {
              e.target.style.display = 'none';
              e.target.nextSibling && (e.target.nextSibling.style.display = 'block');
            }}
          />
        ) : null}
        <div className={`reel-thumb-art art-${hasRealThumb ? 'g1' : (reel.thumb || 'g1')}`}
             style={hasRealThumb ? { display: 'none' } : {}}></div>
        <div className="reel-thumb-overlay">
          <span className="reel-play"><Icon name="play" /></span>
        </div>
        {reel.duration && <span className="reel-duration">{reel.duration}</span>}
      </div>
      <div className="reel-meta">
        <span className="reel-title">{reel.title}</span>
        {reel.views && <span className="reel-views">{reel.views}</span>}
      </div>
    </a>
  );
}

function ReelsSection({ reels, config = {} }) {
  return (
    <section className="reels-section">
      <div className="section-head">
        <h2 className="section-title"><Icon name="play" /> {config.reelsTitle || 'Letzte Reels'}</h2>
        <a href={config.reelsHref || '#'} className="section-link">alle ansehen <Icon name="arrow" /></a>
      </div>
      <div className="reels-grid">
        {reels.map((r) => <ReelCard key={r.id} reel={r} />)}
      </div>
    </section>
  );
}

window.ProfileHeader = ProfileHeader;
window.LiveCard = LiveCard;
window.StatsStrip = StatsStrip;
window.LinksGrid = LinksGrid;
window.VibeCheck = VibeCheck;
window.VideoSection = VideoSection;
window.ReelsSection = ReelsSection;
