// Beat detail page — UC-A1 conversion screen
// Big art + waveform player on left, license/buy block on right (sticky)
// Below: producer card, similar beats, license terms, FAQ, reviews

const BD_Icons = window.SonaraIcons;
const { useState: useStateBD, useEffect: useEffectBD, useMemo: useMemoBD, useRef: useRefBD } = React;

// Mock beat — uses ALL_BEATS[0] if available, otherwise inline
const PICK_BEAT = () => (window.ALL_BEATS && window.ALL_BEATS[2]) || {
  id: 3, title: "Sognando blue moon",
  producer: { name: "Yoshi Beats", init: "Y", verified: true, art: "art-a", followers: 1240, rating: 4.8, reviews: 87, responseTime: "2h", location: "Milano" },
  genre: "Trap", art: "art-a",
  bpm: 140, key: "A min",
  duration: "2:14", plays: 24300, likes: 412,
  price: 49,
};

function BeatDetailPage() {
  const beat = useMemoBD(() => {
    const src = PICK_BEAT();
    // Normalize the producer field — ALL_BEATS has producer as object already
    if (typeof src.producer === "string") {
      return { ...src, producer: { name: src.producer, init: src.producer.charAt(0), verified: true, art: src.art, followers: 1240, rating: 4.8, reviews: 87, responseTime: "2h", location: "Milano" } };
    }
    return {
      ...src,
      producer: src.producer.name ? src.producer : { ...src.producer, name: src.producer, init: "Y", verified: true, art: src.art, followers: 1240, rating: 4.8, reviews: 87, responseTime: "2h", location: "Milano" }
    };
  }, []);

  // Normalize once more, defensively
  const prod = beat.producer && beat.producer.name
    ? beat.producer
    : { name: String(beat.producer || "Yoshi Beats"), init: "Y", verified: true, art: beat.art || "art-a", followers: 1240, rating: 4.8, reviews: 87, responseTime: "2h", location: "Milano" };

  const [selectedLicense, setSelectedLicense] = useStateBD("non-exclusive");
  const [liked, setLiked] = useStateBD(false);
  const [playing, setPlaying] = useStateBD(false);

  const licenses = [
    {
      id: "non-exclusive", label: "Non-esclusiva", price: 49,
      tagline: "Per release indie, demo, social",
      includes: ["MP3 + WAV", "Streaming illimitato", "Distribuzione Spotify/Apple", "Producer mantiene la track", "Credito obbligatorio"],
      limits: ["Max 100k stream/anno", "No sync TV/film", "No re-licensing"],
      popular: true,
    },
    {
      id: "exclusive", label: "Esclusiva", price: 380,
      tagline: "Solo per te, ritirata dal catalogo",
      includes: ["Stems multitraccia (8 tracce)", "Streaming illimitato", "Sync TV/film/spot", "Track ritirata dal catalogo", "Credito opzionale", "Trasferimento copyright"],
      limits: ["Producer mantiene 30% mechanical royalty", "Pagamento singola soluzione"],
      popular: false,
    },
  ];

  const sel = licenses.find(l => l.id === selectedLicense);

  return (
    <div className="page-beat" data-screen-label="Beat detail">
      {/* breadcrumb */}
      <nav className="breadcrumb">
        <a href="Esplora.html">Esplora</a>
        <span className="bc-sep">/</span>
        <a href="Esplora.html">Beat</a>
        <span className="bc-sep">/</span>
        <span className="bc-current">{beat.title}</span>
      </nav>

      <div className="bd-grid">
        {/* LEFT — beat hero */}
        <div className="bd-left">
          {/* Hero card with art + player */}
          <article className={`bd-hero ${beat.art || "art-a"}`}>
            <div className="bd-hero-inner">
              <div className={`bd-hero-art ${beat.art || "art-a"}`}>
                <span className="ic"><BD_Icons.waveform size={64}/></span>
                <span className="bd-hero-genre">{beat.genre}</span>
              </div>
              <div className="bd-hero-body">
                <div className="bd-hero-meta">
                  <span className="chip">{beat.genre}</span>
                  <span className="chip mood">Dark</span>
                  <span className="chip mood">Notturno</span>
                </div>
                <h1 className="bd-hero-title">{beat.title}</h1>
                <a className="bd-hero-prod" href="Producer.html">
                  <span className={`av ${prod.art || "art-a"}`}>{prod.init}</span>
                  <span className="n">{prod.name}</span>
                  {prod.verified && <BD_Icons.verified size={13}/>}
                </a>
                <div className="bd-hero-stats">
                  <span><strong>{beat.bpm}</strong> BPM</span>
                  <span className="dot"/>
                  <span><strong>{beat.key}</strong></span>
                  <span className="dot"/>
                  <span><strong>{(beat.plays/1000).toFixed(1)}k</strong> plays</span>
                  <span className="dot"/>
                  <span><strong>{beat.likes}</strong> like</span>
                </div>
              </div>
            </div>

            {/* Player bar */}
            <div className="bd-player">
              <button className="bd-play-btn" onClick={() => setPlaying(p => !p)}>
                {playing
                  ? <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><rect x="6" y="5" width="4" height="14" rx="1"/><rect x="14" y="5" width="4" height="14" rx="1"/></svg>
                  : <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><polygon points="6 4 20 12 6 20 6 4"/></svg>
                }
              </button>
              <div className="bd-player-mid">
                <div className="bd-waveform">
                  {Array.from({ length: 80 }).map((_, i) => {
                    const h = 20 + Math.abs(Math.sin(i * 0.6) * 30) + Math.abs(Math.cos(i * 0.13) * 20);
                    const played = i < 26;
                    return <span key={i} className={`bar ${played ? "played" : ""}`} style={{ height: `${Math.min(h, 60)}%` }}/>;
                  })}
                </div>
                <div className="bd-player-meta">
                  <span>0:42</span>
                  <span className="bd-watermark">Anteprima · 2:14 totali</span>
                  <span>2:14</span>
                </div>
              </div>
              <div className="bd-player-actions">
                <button className={`bd-icon-btn ${liked ? "liked" : ""}`} onClick={() => setLiked(l => !l)} title="Salva">
                  <svg width="18" height="18" viewBox="0 0 24 24" fill={liked ? "currentColor" : "none"} stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
                    <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/>
                  </svg>
                </button>
                <button className="bd-icon-btn" title="Condividi"><BD_Icons.share size={16}/></button>
                <button className="bd-icon-btn" title="Altro"><BD_Icons.more size={16}/></button>
              </div>
            </div>
          </article>

          {/* Tabs: Descrizione / Stems / Recensioni */}
          <BeatTabs beat={beat}/>

          {/* Producer card */}
          <ProducerInline prod={prod}/>

          {/* Similar beats */}
          <SimilarBeats current={beat.id}/>
        </div>

        {/* RIGHT — buy box (sticky) */}
        <aside className="bd-right">
          <div className="bd-buybox">
            <div className="bd-buybox-head">
              <span className="lbl">Licenze disponibili</span>
              <span className="trust"><BD_Icons.shield size={12}/> Pagamento garantito</span>
            </div>

            <div className="license-options">
              {licenses.map(l => (
                <label key={l.id} className={`license-opt ${selectedLicense === l.id ? "active" : ""}`}>
                  <input type="radio" name="license" checked={selectedLicense === l.id} onChange={() => setSelectedLicense(l.id)}/>
                  <div className="license-opt-body">
                    <div className="license-opt-row1">
                      <span className="lo-label">{l.label}</span>
                      {l.popular && <span className="popular-pill">Popolare</span>}
                      <span className="lo-price">€{l.price}</span>
                    </div>
                    <div className="lo-tagline">{l.tagline}</div>
                  </div>
                </label>
              ))}
            </div>

            <div className="license-detail">
              <div className="ld-section">
                <div className="ld-h"><BD_Icons.check size={12}/> Cosa ottieni</div>
                <ul className="ld-list">
                  {sel.includes.map((x, i) => <li key={i}>{x}</li>)}
                </ul>
              </div>
              <div className="ld-section ld-limits">
                <div className="ld-h"><BD_Icons.flag size={12}/> Limitazioni</div>
                <ul className="ld-list">
                  {sel.limits.map((x, i) => <li key={i}>{x}</li>)}
                </ul>
              </div>
            </div>

            <div className="bd-cta-row">
              <a href="Ordine.html" className="btn-buy">
                <span className="btn-buy-l">Acquista ora</span>
                <span className="btn-buy-p">€{sel.price}</span>
              </a>
              <a href="Messaggi.html" className="btn-secondary-lg">
                <BD_Icons.message size={14}/> Contatta producer
              </a>
            </div>
            <div className="bd-trust-row">
              <span><BD_Icons.shield size={11}/> Escrow Sonara</span>
              <span className="dot"/>
              <span><BD_Icons.clock size={11}/> Download immediato</span>
              <span className="dot"/>
              <span><BD_Icons.flag size={11}/> Rimborso 24h</span>
            </div>
          </div>

          <div className="bd-side-card">
            <div className="bsc-h">In primo piano</div>
            <div className="bsc-feature">
              <BD_Icons.zap size={15}/>
              <div>
                <div className="t">Risposta media in 2h</div>
                <div className="s">Yoshi è online ora · contattalo prima dell'acquisto</div>
              </div>
            </div>
          </div>
        </aside>
      </div>
    </div>
  );
}

// ---------- Tabs ----------
function BeatTabs({ beat }) {
  const [tab, setTab] = useStateBD("desc");
  return (
    <section className="bd-tabs-card">
      <nav className="bd-tabs">
        {[
          ["desc", "Descrizione"],
          ["details", "Dettagli tecnici"],
          ["stems", "Stems & file"],
          ["reviews", "Recensioni · 23"],
        ].map(([id, lbl]) => (
          <button key={id} className={`bd-tab ${tab === id ? "active" : ""}`} onClick={() => setTab(id)}>{lbl}</button>
        ))}
      </nav>
      <div className="bd-tab-body">
        {tab === "desc" && (
          <div className="prose">
            <p>Beat trap dark con atmosfera notturna e 808 grossi, perfetto per cori melodici e voci taglienti. Costruito attorno a un campione di pianoforte filtrato e un basso analogico con saturazione armonica.</p>
            <p>Mixato con ProTools 2024, mastered su SSL G-Series. Lascia spazio in alto per voce in coda e ad-lib. Loop pulito di 8 battute con drop a 1:14.</p>
            <div className="tag-row">
              <span className="tag">Trap</span>
              <span className="tag">Dark</span>
              <span className="tag">Notturno</span>
              <span className="tag">808 heavy</span>
              <span className="tag">Sfera-style</span>
              <span className="tag">Mood: cinematic</span>
            </div>
          </div>
        )}
        {tab === "details" && (
          <div className="bd-details-grid">
            {[
              ["BPM", "140"],
              ["Tonalità", "A minor"],
              ["Time signature", "4/4"],
              ["Durata", "2:14"],
              ["Bars (loop)", "8 + intro 4"],
              ["Drop", "01:14"],
              ["Sample rate", "48kHz / 24-bit"],
              ["Format", "WAV + MP3 320"],
              ["Stems", "8 tracce (su esclusiva)"],
              ["Software", "ProTools 2024"],
              ["Mastering", "SSL G-Series"],
              ["Genere primario", "Trap"],
            ].map(([k, v]) => (
              <div key={k} className="bd-detail">
                <span className="k">{k}</span>
                <span className="v">{v}</span>
              </div>
            ))}
          </div>
        )}
        {tab === "stems" && (
          <div className="bd-stems">
            <div className="bd-stems-note">
              <BD_Icons.shield size={14}/>
              Gli stems sono inclusi solo nella licenza esclusiva. Acquistando, riceverai un .ZIP con 8 tracce separate.
            </div>
            <div className="stems-list">
              {[
                ["Kick", "Heavy 808 sub"],
                ["Snare + claps", "Layered, room verb"],
                ["Hi-hat", "Pattern + rolls"],
                ["Bass 808", "Saturato, glide"],
                ["Piano", "Pad filtrato"],
                ["Synth lead", "Detuned saw"],
                ["FX", "Risers + impacts"],
                ["Master bus", "Track stereo finale"],
              ].map(([n, d]) => (
                <div key={n} className="stem-row">
                  <span className="stem-ic"><BD_Icons.audioFile size={14}/></span>
                  <span className="stem-n">{n}</span>
                  <span className="stem-d">{d}</span>
                  <span className="stem-locked">Esclusiva</span>
                </div>
              ))}
            </div>
          </div>
        )}
        {tab === "reviews" && (
          <div className="bd-reviews">
            <div className="bd-reviews-head">
              <div className="rh-l">
                <div className="rh-num">4.8</div>
                <div className="rh-stars">
                  {[1,2,3,4,5].map(i => <BD_Icons.star key={i} size={14} filled={i <= 4}/>)}
                </div>
                <div className="rh-count">23 recensioni</div>
              </div>
              <div className="rh-r">
                {[
                  [5, 17],
                  [4, 4],
                  [3, 1],
                  [2, 1],
                  [1, 0],
                ].map(([s, c]) => (
                  <div key={s} className="rh-bar">
                    <span className="rh-bar-l">{s}★</span>
                    <span className="rh-bar-track"><span style={{ width: `${(c/23)*100}%` }}/></span>
                    <span className="rh-bar-c">{c}</span>
                  </div>
                ))}
              </div>
            </div>
            <div className="reviews-list">
              {[
                { who: "Marco T.", whoInit: "MT", time: "2 sett", stars: 5, text: "Beat pazzesco, l'808 è perfetto. Yoshi mi ha consegnato gli stems entro 2 ore dall'acquisto." },
                { who: "VV", whoInit: "VV", time: "1 mese", stars: 5, text: "Ho fatto la mia release più grossa con questo beat. Top." },
                { who: "Luca M.", whoInit: "LM", time: "1 mese", stars: 4, text: "Bel beat, avrei preferito un drop più aggressivo ma il mood è giusto." },
              ].map((r, i) => (
                <div key={i} className="review-row">
                  <div className="rev-av">{r.whoInit}</div>
                  <div className="rev-body">
                    <div className="rev-row1">
                      <span className="rev-who">{r.who}</span>
                      <span className="rev-stars">{[1,2,3,4,5].map(x => <BD_Icons.star key={x} size={11} filled={x <= r.stars}/>)}</span>
                      <span className="rev-time">{r.time}</span>
                    </div>
                    <p className="rev-text">{r.text}</p>
                  </div>
                </div>
              ))}
            </div>
            <button className="btn-ghost-sm">Vedi tutte le 23 recensioni</button>
          </div>
        )}
      </div>
    </section>
  );
}

// ---------- Producer inline ----------
function ProducerInline({ prod }) {
  return (
    <section className="prod-inline">
      <div className="pi-head">
        <a href="Producer.html" className="pi-l">
          <div className={`pi-cover ${prod.art || "art-a"}`}>
            <span>{prod.init}</span>
          </div>
          <div className="pi-body">
            <div className="pi-row1">
              <span className="pi-name">{prod.name}</span>
              {prod.verified && <span className="pi-verified"><BD_Icons.verified size={13}/></span>}
            </div>
            <div className="pi-row2">
              <span><BD_Icons.pin size={11}/> {prod.location}</span>
              <span className="dot"/>
              <span><BD_Icons.star size={11} filled/> {prod.rating} · {prod.reviews} recensioni</span>
              <span className="dot"/>
              <span>Risposta in {prod.responseTime}</span>
            </div>
            <div className="pi-row3">
              <span className="g-chip">Trap</span>
              <span className="g-chip">Drill</span>
              <span className="g-chip">Hip-hop</span>
            </div>
          </div>
        </a>
        <div className="pi-actions">
          <a href="Messaggi.html" className="btn-ghost-sm"><BD_Icons.message size={13}/> Contatta</a>
          <a href="Producer.html" className="btn-primary-sm">Vedi profilo <BD_Icons.arrowRight size={12}/></a>
        </div>
      </div>
    </section>
  );
}

// ---------- Similar beats ----------
function SimilarBeats({ current }) {
  const beats = (window.ALL_BEATS || []).filter(b => b.id !== current).slice(0, 4);
  if (beats.length === 0) return null;
  return (
    <section className="similar-beats">
      <div className="section-head">
        <span className="t">Beat simili</span>
        <a href="Esplora.html" className="more">Vedi catalogo <BD_Icons.chevronRight size={13}/></a>
      </div>
      <div className="similar-grid">
        {beats.map(b => (
          <a key={b.id} href="Beat.html" className="similar-card">
            <div className={`sim-art ${b.art || "art-a"}`}>
              <span><BD_Icons.waveform size={20}/></span>
            </div>
            <div className="sim-body">
              <div className="sim-title">{b.title}</div>
              <div className="sim-prod">{typeof b.producer === "string" ? b.producer : (b.producer && b.producer.name) || "Yoshi"}</div>
              <div className="sim-meta">
                <span>{b.bpm} BPM</span>
                <span className="dot"/>
                <span>€{b.price || 49}</span>
              </div>
            </div>
          </a>
        ))}
      </div>
    </section>
  );
}

window.BeatDetailPage = BeatDetailPage;
