/* =========================================================
   Tappt — rich embeds (Spotify · YouTube · TikTok)
   Parses a pasted URL into a provider iframe. Shared by the
   dashboard profile, edit preview, and public page.
   ========================================================= */

/* Detect provider + build the official embed URL from any pasted link. */
function parseEmbed(raw) {
  if (!raw) return null;
  const url = String(raw).trim();

  // YouTube — watch?v=, youtu.be/, /shorts/, /embed/
  let m = url.match(/(?:youtube\.com\/(?:watch\?(?:.*&)?v=|embed\/|shorts\/|live\/)|youtu\.be\/)([\w-]{11})/i);
  if (m) return { provider: 'youtube', id: m[1], embed: 'https://www.youtube-nocookie.com/embed/' + m[1], ratio: 56.25 };

  // Spotify — track / album / playlist / episode / show / artist
  m = url.match(/open\.spotify\.com\/(?:intl-[a-z]+\/)?(track|album|playlist|episode|show|artist)\/([A-Za-z0-9]+)/i);
  if (m) {
    const tall = (m[1] === 'playlist' || m[1] === 'album' || m[1] === 'show' || m[1] === 'artist');
    return { provider: 'spotify', kind: m[1], id: m[2], embed: 'https://open.spotify.com/embed/' + m[1] + '/' + m[2], height: m[1] === 'episode' ? 232 : (tall ? 352 : 152) };
  }

  // TikTok — /video/{id} or vm.tiktok short links (need full URL for id)
  m = url.match(/tiktok\.com\/(?:@[\w.-]+\/video\/|v\/|embed\/v2\/)?(\d{6,})/i);
  if (m) return { provider: 'tiktok', id: m[1], embed: 'https://www.tiktok.com/embed/v2/' + m[1], ratio: 150 };

  return null;
}

const EMBED_PROVIDERS = [
  { id: 'spotify', label: 'Spotify', hint: 'Track, album, playlist or podcast link', ph: 'open.spotify.com/track/…' },
  { id: 'youtube', label: 'YouTube', hint: 'Any video, Short or live link', ph: 'youtube.com/watch?v=…' },
  { id: 'tiktok',  label: 'TikTok',  hint: 'A video link (not a profile)', ph: 'tiktok.com/@user/video/…' },
];

/* One embedded player card. lazy=true renders a tap-to-load poster first
   (keeps profiles fast when there are several embeds). */
function EmbedCard({ item, eager }) {
  const e = (item && item.parsed) || parseEmbed(item && item.url);
  const [live, setLive] = React.useState(!!eager);
  if (!e) return null;
  const P = (window.platById ? window.platById(e.provider) : null);

  if (e.provider === 'spotify') {
    return (
      <div className="embed-card embed-spotify">
        <iframe title="Spotify" src={e.embed + '?utm_source=tappt'} width="100%" height={e.height || 152}
          frameBorder="0" loading="lazy" allow="autoplay; clipboard-write; encrypted-media; fullscreen; picture-in-picture"
          style={{ borderRadius: 14, display: 'block' }}></iframe>
      </div>
    );
  }

  // YouTube + TikTok — facade until tapped (perf + no autoplay surprises)
  const ratio = e.ratio || 56.25;
  if (!live) {
    return (
      <button className={'embed-card embed-facade prov-' + e.provider} style={{ paddingTop: ratio + '%' }} onClick={() => setLive(true)} aria-label={'Play ' + e.provider}>
        {item && item.thumb && <img className="embed-thumb" src={item.thumb} alt="" />}
        <span className="embed-shade" />
        <span className="embed-play">{window.I && window.I.play ? window.I.play({ width: 26, height: 26 }) : '▶'}</span>
        <span className="embed-badge">{P ? <span className="eb-ic"><BrandIcon id={e.provider} size={20} /></span> : null}{e.provider === 'youtube' ? 'Watch on YouTube' : 'Watch on TikTok'}</span>
      </button>
    );
  }
  return (
    <div className={'embed-card embed-live prov-' + e.provider} style={{ paddingTop: ratio + '%' }}>
      <iframe title={e.provider} src={e.embed + (e.provider === 'youtube' ? '?autoplay=1&rel=0' : '')}
        frameBorder="0" loading="lazy" allowFullScreen
        allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
        style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', border: 0, borderRadius: 14 }}></iframe>
    </div>
  );
}

/* The whole Embeds section on a profile. */
function EmbedRail({ user }) {
  const items = (user.embeds || []).filter((x) => x && x.url);
  if (items.length === 0) return null;
  return (
    <div className="embed-rail">
      {items.map((it, i) => <EmbedCard key={it.id || i} item={it} eager={it.provider === 'spotify'} />)}
    </div>
  );
}

window.parseEmbed = parseEmbed;
window.EMBED_PROVIDERS = EMBED_PROVIDERS;
window.EmbedCard = EmbedCard;
window.EmbedRail = EmbedRail;

/* ---- editor (used inside the Embeds section card in edit mode) ---- */
function EmbedEditor({ d, set }) {
  const [url, setUrl] = React.useState('');
  const [err, setErr] = React.useState('');
  const list = d.embeds || [];
  const add = () => {
    const parsed = parseEmbed(url);
    if (!parsed) { setErr("Hmm — paste a full Spotify, YouTube or TikTok link."); return; }
    set({ embeds: [...list, { id: 'e' + Date.now(), url: url.trim(), provider: parsed.provider }] });
    setUrl(''); setErr('');
  };
  const remove = (i) => set({ embeds: list.filter((_, j) => j !== i) });
  const move = (i, dir) => {
    const j = i + dir; if (j < 0 || j >= list.length) return;
    const next = list.slice(); const t = next[i]; next[i] = next[j]; next[j] = t;
    set({ embeds: next });
  };
  const cur = parseEmbed(url);
  return (
    <div className="embed-editor">
      <div className="embed-add">
        <input className="input" placeholder="Paste a Spotify, YouTube or TikTok link" value={url}
          onChange={(e) => { setUrl(e.target.value); setErr(''); }} onKeyDown={(e) => { if (e.key === 'Enter') add(); }} />
        <button className={'embed-add-btn' + (cur ? ' ready' : '')} onClick={add} aria-label="Add embed">{window.I && window.I.plus ? window.I.plus({ width: 20, height: 20 }) : '+'}</button>
      </div>
      <div className="embed-provrow">
        {EMBED_PROVIDERS.map((p) => (
          <span key={p.id} className={'embed-prov-chip' + (cur && cur.provider === p.id ? ' on' : '')}><BrandIcon id={p.id} size={18} />{p.label}</span>
        ))}
      </div>
      {err && <div className="embed-err">{err}</div>}
      {list.length === 0
        ? <div className="embed-empty">Add a track, video or playlist and it plays right on your profile.</div>
        : <div className="embed-list">
            {list.map((it, i) => {
              const e = parseEmbed(it.url) || {};
              return (
                <div className="embed-li" key={it.id || i}>
                  <span className="embed-li-ic"><BrandIcon id={e.provider || it.provider || 'custom'} size={30} /></span>
                  <span className="embed-li-meta"><b>{(e.provider || it.provider || 'link')}</b><span>{it.url}</span></span>
                  <div className="embed-li-tools">
                    <button onClick={() => move(i, -1)} disabled={i === 0} aria-label="Up">↑</button>
                    <button onClick={() => move(i, 1)} disabled={i === list.length - 1} aria-label="Down">↓</button>
                    <button className="eli-x" onClick={() => remove(i)} aria-label="Remove">✕</button>
                  </div>
                </div>
              );
            })}
          </div>}
    </div>
  );
}
window.EmbedEditor = EmbedEditor;
