// Shared UI primitives for NOICE Premium Landing — Cinematic Dark

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

// === LOGO ===
function NoiceLogo({ color = 'currentColor', size = 22 }) {
  return (
    <div className="noice-logo" style={{ fontSize: size, color }}>
      NOICE<span className="dot">.</span>
    </div>
  );
}

// === ICONS ===
const Icon = ({ name, size = 20, stroke = 2 }) => {
  const paths = {
    noads: <><circle cx="12" cy="12" r="9" /><path d="M5 5l14 14" /></>,
    lock: <><rect x="5" y="11" width="14" height="10" rx="2" /><path d="M8 11V7a4 4 0 0 1 8 0v4" /></>,
    podcast: <><circle cx="12" cy="11" r="3" /><path d="M6.5 16.5a8 8 0 1 1 11 0" /><path d="M9 14a5 5 0 0 1 6 0" /><path d="M10 20h4" /><path d="M12 17v3" /></>,
    film: <><rect x="3" y="5" width="18" height="14" rx="2" /><path d="M7 5v14M17 5v14M3 9h4M17 9h4M3 15h4M17 15h4" /></>,
    book: <><path d="M4 5a2 2 0 0 1 2-2h12v16H6a2 2 0 0 0-2 2V5z" /><path d="M4 19a2 2 0 0 1 2-2h12" /></>,
    download: <><path d="M12 3v12m0 0l-4-4m4 4l4-4" /><path d="M4 17v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2" /></>,
    play: <path d="M8 5v14l11-7z" fill="currentColor" stroke="none" />,
    pause: <><rect x="7" y="5" width="3" height="14" fill="currentColor" stroke="none" /><rect x="14" y="5" width="3" height="14" fill="currentColor" stroke="none" /></>,
    chev: <path d="M6 9l6 6 6-6" />,
    check: <path d="M5 12l5 5L20 7" />,
    sparkle: <path d="M12 3l2.5 6.5L21 12l-6.5 2.5L12 21l-2.5-6.5L3 12l6.5-2.5L12 3z" fill="currentColor" stroke="none" />,
    arrow: <path d="M5 12h14M13 6l6 6-6 6" />,
    close: <path d="M6 6l12 12M6 18L18 6" />,
    star: <path d="M12 3l2.5 6 6.5.5-5 4.5 1.5 6.5L12 17l-5.5 3.5L8 14 3 9.5 9.5 9 12 3z" fill="currentColor" stroke="none" />,
    device: <><rect x="3" y="4" width="18" height="12" rx="2" /><path d="M8 20h8M12 16v4" /></>,
    phone: <><rect x="7" y="3" width="10" height="18" rx="2" /><path d="M11 19h2" /></>,
    globe: <><circle cx="12" cy="12" r="9" /><path d="M3 12h18M12 3c3 3 3 15 0 18M12 3c-3 3-3 15 0 18" /></>,
  };
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={stroke} strokeLinecap="round" strokeLinejoin="round">
      {paths[name]}
    </svg>
  );
};

// === ART PLACEHOLDER ===
function ArtTile({ hue = 280, label = '', sat = 70, light = 55 }) {
  const bg = `linear-gradient(135deg,
    hsl(${hue}, ${sat}%, ${light}%) 0%,
    hsl(${(hue + 30) % 360}, ${sat}%, ${light - 15}%) 50%,
    hsl(${(hue + 60) % 360}, ${sat - 10}%, ${light - 25}%) 100%)`;
  return (
    <div style={{ width: '100%', height: '100%', background: bg, position: 'relative', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <svg viewBox="0 0 100 100" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', opacity: 0.3, mixBlendMode: 'overlay' }}>
        <defs>
          <pattern id={`dots-${hue}`} width="8" height="8" patternUnits="userSpaceOnUse">
            <circle cx="4" cy="4" r="0.5" fill="white" />
          </pattern>
        </defs>
        <rect width="100" height="100" fill={`url(#dots-${hue})`} />
      </svg>
      <div style={{ fontFamily: 'Space Grotesk, monospace', fontSize: 9, color: 'rgba(255,255,255,0.7)', fontWeight: 600, letterSpacing: '0.08em', textTransform: 'uppercase', padding: 6, zIndex: 1, textAlign: 'center' }}>
        {label || `HUE ${hue}`}
      </div>
    </div>
  );
}

// === BADGE ===
function Badge({ type }) {
  const styles = {
    PREMIUM: { bg: '#FAD810', color: '#141414' },
    VIP: { bg: '#FAD810', color: '#141414' },
    NEW: { bg: '#10B981', color: 'white' },
    EARLY: { bg: '#F43F5E', color: 'white' },
    AUDIOBOOK: { bg: 'rgba(255,255,255,0.9)', color: '#141414' },
  };
  const s = styles[type] || styles.PREMIUM;
  return (
    <span style={{ fontSize: 9, fontWeight: 800, padding: '3px 7px', borderRadius: 4, letterSpacing: '0.05em', background: s.bg, color: s.color, textTransform: 'uppercase', whiteSpace: 'nowrap' }}>{type}</span>
  );
}

// === CONTENT TILE ===
function ContentTile({ item, size = 160, showTitle = true, creatorMode = false }) {
  return (
    <div className={`tile${creatorMode ? ' tile-creator-mode' : ''}`} style={{ width: size, height: size }}>
      <ArtTile hue={item.hue} label={creatorMode ? '' : item.host} />
      {item.badge && (
        <div className="tile-host">
          <Badge type={item.badge} />
        </div>
      )}
      {creatorMode ? (
        <>
          <div className="tile-creator-name">{item.host}</div>
          <div className="tile-episode-title">{item.title}</div>
        </>
      ) : (
        showTitle && <div className="tile-title">{item.title}</div>
      )}
    </div>
  );
}

// === MARQUEE ROW (content tiles) ===
function MarqueeRow({ items, size = 140, reverse = false, duration = 50, creatorMode = false }) {
  const doubled = [...items, ...items];
  return (
    <div className="marquee-wrap" style={{ overflow: 'hidden', width: '100%' }}>
      <div className={`marquee-track horizontal${reverse ? ' reverse' : ''}`} style={{ animationDuration: `${duration}s` }}>
        {doubled.map((it, i) => (
          <ContentTile key={i} item={it} size={size} creatorMode={creatorMode} />
        ))}
      </div>
    </div>
  );
}

// === CREATOR TILE ===
function CreatorTile({ creator, size = 100 }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10, flexShrink: 0, width: size + 24 }}>
      <div style={{ width: size, height: size, borderRadius: '50%', overflow: 'hidden', border: '2px solid rgba(255,255,255,0.12)' }}>
        <ArtTile hue={creator.hue} label="" />
      </div>
      <div style={{ textAlign: 'center', padding: '0 4px' }}>
        <div style={{ fontSize: 13, fontWeight: 700, color: 'white', whiteSpace: 'nowrap' }}>{creator.name}</div>
        <div style={{ fontSize: 11, color: '#767676', marginTop: 2, whiteSpace: 'nowrap' }}>{creator.subtitle}</div>
      </div>
    </div>
  );
}

// === CREATOR MARQUEE ===
function CreatorMarquee({ items, size = 100, reverse = false, duration = 40 }) {
  const doubled = [...items, ...items];
  return (
    <div className="marquee-wrap" style={{ overflow: 'hidden', width: '100%' }}>
      <div className={`marquee-track horizontal${reverse ? ' reverse' : ''}`} style={{ gap: 28, alignItems: 'flex-start', animationDuration: `${duration}s` }}>
        {doubled.map((creator, i) => (
          <CreatorTile key={i} creator={creator} size={size} />
        ))}
      </div>
    </div>
  );
}

// === GENRE MARQUEE ===
function GenreMarquee({ items, reverse = false, accent = '#FAD810', duration = 30 }) {
  const doubled = [...items, ...items];
  return (
    <div className="marquee-wrap" style={{ overflow: 'hidden', width: '100%' }}>
      <div className={`marquee-track horizontal${reverse ? ' reverse' : ''}`} style={{ gap: 10, animationDuration: `${duration}s` }}>
        {doubled.map((genre, i) => {
          const isAccent = i % 7 === 0;
          return (
            <span key={i} style={{
              padding: '10px 22px', borderRadius: 999, flexShrink: 0,
              background: isAccent ? 'rgba(250,216,16,0.08)' : 'rgba(255,255,255,0.04)',
              border: `1px solid ${isAccent ? 'rgba(250,216,16,0.35)' : 'rgba(255,255,255,0.1)'}`,
              fontSize: 14, fontWeight: isAccent ? 600 : 400,
              color: isAccent ? accent : '#DEDEDE',
              whiteSpace: 'nowrap',
            }}>{genre}</span>
          );
        })}
      </div>
    </div>
  );
}

// === AUDIO PREVIEW PLAYER ===
function AudioPreview({ title, host, hue = 280, dark = false, accent = null }) {
  const [playing, setPlaying] = useState(false);
  const [progress, setProgress] = useState(0);
  useEffect(() => {
    if (!playing) return;
    const id = setInterval(() => {
      setProgress(p => {
        if (p >= 100) { setPlaying(false); return 0; }
        return p + 0.4;
      });
    }, 100);
    return () => clearInterval(id);
  }, [playing]);
  const bg = dark ? 'rgba(255,255,255,0.06)' : 'white';
  const border = dark ? '1px solid rgba(255,255,255,0.1)' : '1px solid rgba(0,0,0,0.06)';
  const shadow = dark ? 'none' : '0 4px 20px -8px rgba(26,15,46,0.15)';
  const textColor = dark ? '#fff' : '#1A0F2E';
  const subColor = dark ? 'rgba(255,255,255,0.6)' : '#6B7280';
  const playBtnBg = accent || 'linear-gradient(135deg, #8B5CF6, #D946EF)';
  const playBtnColor = accent ? '#141414' : 'white';
  return (
    <div className="preview-player" style={{ background: bg, border, boxShadow: shadow, color: textColor }}>
      <div style={{ width: 56, height: 56, borderRadius: 10, overflow: 'hidden', flexShrink: 0 }}>
        <ArtTile hue={hue} label="" />
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 700, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{title}</div>
        <div style={{ fontSize: 11, color: subColor, marginTop: 2 }}>{host}</div>
        <div style={{ marginTop: 8, height: 3, background: dark ? 'rgba(255,255,255,0.1)' : '#F3F4F6', borderRadius: 2, overflow: 'hidden' }}>
          <div style={{ width: `${progress}%`, height: '100%', background: `linear-gradient(90deg, hsl(${hue},70%,60%), hsl(${hue+40},70%,60%))`, transition: 'width .1s linear' }} />
        </div>
      </div>
      <button onClick={() => setPlaying(p => !p)} className="play-btn" style={{ background: playBtnBg, color: playBtnColor }}>
        <Icon name={playing ? 'pause' : 'play'} size={18} />
      </button>
    </div>
  );
}

// === FAQ ACCORDION ===
function FAQList({ items, dark = false }) {
  const [open, setOpen] = useState(0);
  return (
    <div>
      {items.map((it, i) => (
        <div key={i} className={`faq-item ${open === i ? 'open' : ''}`} style={{ borderColor: dark ? 'rgba(255,255,255,0.1)' : 'rgba(0,0,0,0.08)' }}>
          <button className="faq-q" onClick={() => setOpen(open === i ? -1 : i)} style={{ color: dark ? '#fff' : '#1A0F2E' }}>
            <span>{it.q}</span>
            <span className="chev"><Icon name="chev" size={18} /></span>
          </button>
          <div className="faq-a" style={{ color: dark ? 'rgba(255,255,255,0.7)' : '#6B7280' }}>
            {it.a}
          </div>
        </div>
      ))}
    </div>
  );
}

// === COUNTDOWN ===
function Countdown({ compact = false }) {
  const [time, setTime] = useState({ d: 2, h: 14, m: 32, s: 18 });
  useEffect(() => {
    const id = setInterval(() => {
      setTime(t => {
        let { d, h, m, s } = t;
        s--;
        if (s < 0) { s = 59; m--; }
        if (m < 0) { m = 59; h--; }
        if (h < 0) { h = 23; d--; }
        if (d < 0) return { d: 2, h: 14, m: 32, s: 18 };
        return { d, h, m, s };
      });
    }, 1000);
    return () => clearInterval(id);
  }, []);
  const pad = n => String(n).padStart(2, '0');
  const cellStyle = {
    padding: compact ? '4px 8px' : '8px 14px',
    borderRadius: 8,
    background: 'rgba(26,15,46,0.85)',
    color: 'white',
    fontFamily: 'Space Grotesk, monospace',
    fontWeight: 700,
    fontSize: compact ? 14 : 20,
    minWidth: compact ? 36 : 54,
    textAlign: 'center',
    fontVariantNumeric: 'tabular-nums',
  };
  return (
    <div style={{ display: 'inline-flex', gap: 8, alignItems: 'center' }}>
      {[{ v: time.d, l: 'HARI' }, { v: time.h, l: 'JAM' }, { v: time.m, l: 'MNT' }, { v: time.s, l: 'DTK' }].map((c, i) => (
        <React.Fragment key={i}>
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
            <div style={cellStyle}>{pad(c.v)}</div>
            {!compact && <div style={{ fontSize: 9, fontWeight: 600, opacity: 0.7, marginTop: 2, letterSpacing: '0.08em' }}>{c.l}</div>}
          </div>
          {i < 3 && <div style={{ color: '#141414', fontSize: compact ? 14 : 20, fontWeight: 700, opacity: 0.5 }}>:</div>}
        </React.Fragment>
      ))}
    </div>
  );
}

// === AVATAR ===
function Avatar({ hue = 280, size = 48, name = '' }) {
  const initials = name.split(' ').slice(0, 2).map(n => n[0]).join('');
  return (
    <div style={{ width: size, height: size, borderRadius: '50%', overflow: 'hidden', background: `linear-gradient(135deg, hsl(${hue},70%,60%), hsl(${(hue+40)%360},70%,55%))`, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'white', fontWeight: 700, fontSize: size * 0.35, flexShrink: 0 }}>{initials}</div>
  );
}

Object.assign(window, {
  NoiceLogo, Icon, ArtTile, Badge, ContentTile,
  MarqueeRow, CreatorTile, CreatorMarquee, GenreMarquee,
  AudioPreview, FAQList, Countdown, Avatar,
});
