/* HelpMe — Place Detail + AI Audio Narrative player */

const BARS = Array.from({ length: 44 }, (_, i) => 22 + Math.round(26 * Math.abs(Math.sin(i * 1.3)) + (i % 5) * 4));
const fmt = (s) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, '0')}`;

function LangStrip({ active, onPick, dark = true }) {
  return (
    <div style={{ display: 'flex', gap: 9 }}>
      {['EN', 'FR', 'KR', 'ZH', 'JP'].map(c => {
        const on = active === c;
        return (
          <button key={c} onClick={() => onPick(c)} style={{
            flex: 1, padding: '11px 0', borderRadius: 12, cursor: 'pointer',
            fontFamily: SANS, fontWeight: 800, fontSize: 14, letterSpacing: 0.4,
            background: on ? T.gold : (dark ? 'rgba(255,255,255,0.06)' : T.white),
            color: on ? '#fff' : (dark ? '#fff' : T.ink),
            border: on ? 'none' : `1px solid ${dark ? 'rgba(255,255,255,0.22)' : T.line}`,
          }}>{c}</button>
        );
      })}
    </div>
  );
}

function QuickFact({ f }) {
  return (
    <div style={{ background: T.white, border: `1px solid ${T.line}`, borderRadius: 14, padding: '13px 15px' }}>
      <div style={{ fontFamily: SANS, fontSize: 12.5, color: T.muted, fontWeight: 600 }}>{f.label}</div>
      <div style={{ fontFamily: SANS, fontSize: 16, color: T.ink, fontWeight: 800, marginTop: 3 }}>{f.value}</div>
    </div>
  );
}

function PlaceDetail({ place, community, onBack, onBook, onOpenAudio, onOpenCommunity, onWrite, aiLearning, lang, setLang }) {
  const p = place;
  const [fav, setFav] = React.useState(false);
  const [g, setG] = React.useState(0);

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: T.cream, position: 'relative' }}>
      <div style={{ flex: 1, overflowY: 'auto' }}>
        {/* hero */}
        <Img src={p.hero} grad={p.grad} style={{ height: 290 }}
          overlay={<>
            <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg,rgba(8,18,32,0.45),rgba(0,0,0,0) 35%,rgba(8,18,32,0.35))' }} />
            <StatusBar light />
            <div style={{ position: 'absolute', top: 50, left: 18, right: 18, display: 'flex', justifyContent: 'space-between' }}>
              <button onClick={onBack} style={iconBtn}><Icon name="arrow-left" size={22} color="#fff" /></button>
              <button onClick={() => setFav(!fav)} style={iconBtn}><Icon name="heart" size={22} color={fav ? T.gold : '#fff'} fill={fav ? T.gold : 'none'} /></button>
            </div>
            <div onClick={onOpenCommunity} style={{ position: 'absolute', bottom: 16, left: 18, display: 'inline-flex', alignItems: 'center', gap: 6, background: 'rgba(8,18,32,0.6)', backdropFilter: 'blur(6px)', padding: '8px 13px', borderRadius: 11, cursor: 'pointer' }}>
              <Icon name="star" size={15} color={T.gold} />
              <span style={{ fontFamily: SANS, fontWeight: 700, fontSize: 14, color: '#fff' }}>{p.rating} · {p.reviews.toLocaleString()} reviews</span>
              <Icon name="chevron-right" size={15} color="rgba(255,255,255,0.7)" />
            </div>
          </>} />

        {/* language strip on navy */}
        <div style={{ background: T.navy, padding: '14px 18px' }}>
          <LangStrip active={lang} onPick={setLang} />
        </div>

        <div style={{ padding: '20px 22px 140px' }}>
          <div>
            <h1 style={{ fontFamily: DISP, fontWeight: 800, fontSize: 33, color: T.ink, margin: 0, lineHeight: 1.05, whiteSpace: 'nowrap' }}>{p.name}</h1>
            <span style={{ fontFamily: SANS, fontSize: 16, color: T.muted }}>{p.khmer}</span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginTop: 9, flexWrap: 'wrap' }}>
            <Meta icon="map-pin" text={p.location} />
            <Dot /><Meta icon="clock" text={`Opens ${p.opens}`} />
            {p.unesco && <><Dot /><Meta icon="globe" text="UNESCO" /></>}
          </div>

          {/* AI narrative card */}
          <div onClick={onOpenAudio} className="gw-press" style={{ marginTop: 18, background: T.navy, borderRadius: 18, padding: 16, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{ width: 54, height: 54, borderRadius: 999, background: T.gold, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, boxShadow: '0 6px 16px rgba(207,154,53,0.45)' }}>
              <Icon name="play" size={22} color="#fff" />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, whiteSpace: 'nowrap' }}>
                <Icon name="sparkle" size={15} color={T.gold} />
                <span style={{ fontFamily: SANS, fontWeight: 700, fontSize: 15.5, color: '#fff' }}>AI Audio Narrative</span>
              </div>
              <div style={{ fontFamily: SANS, fontSize: 12.5, color: 'rgba(255,255,255,0.6)', marginTop: 2, whiteSpace: 'nowrap' }}>
                {p.narration.length} chapters · {fmt(p.narration.reduce((a, c) => a + c.dur, 0))} · in {lang}
              </div>
              <div style={{ height: 4, borderRadius: 999, background: 'rgba(255,255,255,0.15)', marginTop: 9, overflow: 'hidden' }}>
                <div style={{ width: '27%', height: '100%', background: T.gold }} />
              </div>
            </div>
          </div>

          {/* blurb */}
          <p style={{ fontFamily: SANS, fontSize: 16, lineHeight: 1.62, color: T.body, marginTop: 20, textWrap: 'pretty' }}>{p.blurb}</p>

          {/* quick facts */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 11, marginTop: 8 }}>
            {p.quickFacts.map(f => <QuickFact key={f.label} f={f} />)}
          </div>

          {/* why it matters */}
          <h2 style={{ fontFamily: DISP, fontWeight: 700, fontSize: 22, color: T.ink, margin: '26px 0 12px' }}>Why it matters</h2>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {p.facts.map((f, i) => (
              <div key={i} style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
                <div style={{ width: 26, height: 26, borderRadius: 8, background: T.goldBg, color: T.goldDk, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: DISP, fontWeight: 700, fontSize: 14 }}>{i + 1}</div>
                <span style={{ fontFamily: SANS, fontSize: 14.5, lineHeight: 1.5, color: T.body, textWrap: 'pretty' }}>{f}</span>
              </div>
            ))}
          </div>

          {/* gallery */}
          <h2 style={{ fontFamily: DISP, fontWeight: 700, fontSize: 22, color: T.ink, margin: '26px 0 12px' }}>Gallery</h2>
          <Img src={p.gallery[g]} grad={p.grad} radius={16} style={{ height: 200 }} />
          {p.gallery.length > 1 && (
            <div style={{ display: 'flex', gap: 9, marginTop: 10 }}>
              {p.gallery.map((src, i) => (
                <Img key={i} src={src} grad={p.grad} radius={10} onClick={() => setG(i)}
                  style={{ flex: 1, height: 54, cursor: 'pointer', outline: g === i ? `2px solid ${T.gold}` : 'none', outlineOffset: 2 }} />
              ))}
            </div>
          )}

          {/* visit info */}
          <div style={{ background: T.white, border: `1px solid ${T.line}`, borderRadius: 16, padding: 16, marginTop: 24 }}>
            <InfoRow icon="clock" label="Opening hours" value={`${p.opens} – 6:00 PM daily`} />
            <Sep /><InfoRow icon="ticket" label="Entry pass" value={`$${p.price} · 1-day Angkor Pass`} />
            <Sep /><InfoRow icon="headphones" label="Audio guide" value="Included · 6 languages" />
            <Sep /><InfoRow icon="shield-check" label="Verified sellers" value="Booked via APSARA partners" />
          </div>

          {/* community — reviews, stories, tips, photos, corrections */}
          {community && <div style={{ marginTop: 30 }}>
            <CommunitySection data={community} onOpenAll={onOpenCommunity} onWrite={onWrite} aiLearning={aiLearning} />
          </div>}
        </div>
      </div>

      {/* sticky CTA */}
      <div style={{ flexShrink: 0, padding: '14px 22px 20px', background: T.cream, borderTop: `1px solid ${T.line}`, display: 'flex', gap: 12, alignItems: 'center' }}>
        <div>
          <div style={{ fontFamily: SANS, fontSize: 12, color: T.muted, fontWeight: 600 }}>From</div>
          <div style={{ fontFamily: SANS, fontWeight: 800, fontSize: 22, color: T.ink }}>${p.price}<span style={{ fontSize: 13, fontWeight: 600, color: T.muted }}>/adult</span></div>
        </div>
        <PrimaryBtn onClick={onBook} icon="arrow-right" style={{ flex: 1 }}>Book Tickets</PrimaryBtn>
      </div>
    </div>
  );
}

const iconBtn = { width: 44, height: 44, borderRadius: 13, background: 'rgba(8,18,32,0.5)', backdropFilter: 'blur(8px)', border: '1px solid rgba(255,255,255,0.18)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' };
const Dot = () => <span style={{ width: 4, height: 4, borderRadius: 9, background: T.muted }} />;
function Meta({ icon, text }) { return <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontFamily: SANS, fontSize: 14.5, color: T.body, fontWeight: 500, whiteSpace: 'nowrap' }}><Icon name={icon} size={15} color={T.muted} />{text}</span>; }
function Sep() { return <div style={{ height: 1, background: T.line, margin: '13px 0' }} />; }
function InfoRow({ icon, label, value }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 13 }}>
      <div style={{ width: 38, height: 38, borderRadius: 11, background: T.cream, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}><Icon name={icon} size={19} color={T.navy} /></div>
      <div style={{ flex: 1 }}>
        <div style={{ fontFamily: SANS, fontSize: 12.5, color: T.muted, fontWeight: 600 }}>{label}</div>
        <div style={{ fontFamily: SANS, fontSize: 15, color: T.ink, fontWeight: 700 }}>{value}</div>
      </div>
    </div>
  );
}

/* ── docked AI audio player ── */
function AudioPlayer({ place, lang, setLang, onClose }) {
  const p = place || HM.PLACES[0];
  const [ch, setCh] = React.useState(0);
  const [playing, setPlaying] = React.useState(true);
  const [t, setT] = React.useState(72);
  const [speed, setSpeed] = React.useState(1);
  const dur = p.narration[ch].dur;
  const speeds = [1, 1.25, 1.5, 0.75];
  const noAnim = typeof window !== 'undefined' && window.__noAnim;
  const [closing, setClosing] = React.useState(false);
  const requestClose = () => { if (noAnim) return onClose(); setClosing(true); setTimeout(onClose, 280); };

  React.useEffect(() => {
    if (!playing) return;
    const id = setInterval(() => setT(x => {
      const n = x + speed;
      if (n >= dur) { return 0; }
      return n;
    }), 1000);
    return () => clearInterval(id);
  }, [playing, speed, dur]);

  const pct = Math.min(100, (t / dur) * 100);
  const playedBars = Math.round((pct / 100) * BARS.length);

  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 60, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end' }}>
      <div onClick={requestClose} className={closing ? 'gw-back-out' : 'gw-back-in'} style={{ position: 'absolute', inset: 0, background: 'rgba(8,18,32,0.5)', backdropFilter: 'blur(2px)' }} />
      <div className={closing ? 'gw-sheet-out' : 'gw-sheet-in'} style={{ position: 'relative', background: T.navy, borderTopLeftRadius: 28, borderTopRightRadius: 28, padding: '12px 22px 28px', boxShadow: '0 -20px 50px rgba(0,0,0,0.4)' }}>
        <div style={{ width: 42, height: 5, borderRadius: 999, background: 'rgba(255,255,255,0.25)', margin: '0 auto 18px' }} />

        <div style={{ display: 'flex', alignItems: 'center', gap: 13 }}>
          <div style={{ width: 50, height: 50, borderRadius: 13, background: 'rgba(255,255,255,0.08)', border: '1px solid rgba(255,255,255,0.12)', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <Icon name="mic" size={22} color={T.gold} />
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontFamily: SANS, fontWeight: 700, fontSize: 16, color: '#fff', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{p.name} — AI Audio Guide</div>
            <div style={{ fontFamily: SANS, fontSize: 12.5, color: 'rgba(255,255,255,0.6)' }}>Narrated by GoWithMe AI · Chapter {ch + 1} of {p.narration.length}</div>
          </div>
          <button onClick={requestClose} style={{ width: 38, height: 38, borderRadius: 11, background: 'rgba(255,255,255,0.08)', border: '1px solid rgba(255,255,255,0.12)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name="x" size={18} color="#fff" />
          </button>
        </div>

        {/* chapter title + text */}
        <div style={{ marginTop: 16, background: 'rgba(255,255,255,0.05)', borderRadius: 14, padding: 14 }}>
          <div style={{ fontFamily: DISP, fontWeight: 700, fontSize: 17, color: '#fff' }}>{p.narration[ch].title}</div>
          <div style={{ fontFamily: SANS, fontSize: 13.5, lineHeight: 1.55, color: 'rgba(255,255,255,0.72)', marginTop: 6, textWrap: 'pretty' }}>{p.narration[ch].text}</div>
        </div>

        {/* waveform */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 3, height: 46, marginTop: 18 }}>
          {BARS.map((h, i) => (
            <div key={i} style={{
              flex: 1, height: h, borderRadius: 999, transition: 'background .2s',
              background: i < playedBars ? T.gold : 'rgba(255,255,255,0.18)',
              animation: playing && i >= playedBars - 2 && i <= playedBars + 1 ? 'wave 0.7s ease-in-out infinite alternate' : 'none',
              animationDelay: `${(i % 6) * 0.08}s`,
            }} />
          ))}
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 8, fontFamily: SANS, fontSize: 12.5, color: 'rgba(255,255,255,0.6)' }}>
          <span>{fmt(t)}</span><span>{fmt(dur)}</span>
        </div>

        {/* controls */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 14 }}>
          <Ctrl icon="shuffle" onClick={() => {}} />
          <Ctrl icon="skip-back" onClick={() => { setCh(Math.max(0, ch - 1)); setT(0); }} />
          <button onClick={() => setPlaying(!playing)} style={{ width: 64, height: 64, borderRadius: 999, background: T.gold, border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: '0 8px 20px rgba(207,154,53,0.5)' }}>
            <Icon name={playing ? 'pause' : 'play'} size={28} color="#fff" />
          </button>
          <Ctrl icon="skip-fwd" onClick={() => { setCh(Math.min(p.narration.length - 1, ch + 1)); setT(0); }} />
          <button onClick={() => setSpeed(speeds[(speeds.indexOf(speed) + 1) % speeds.length])} style={{ width: 48, height: 48, borderRadius: 13, background: 'rgba(255,255,255,0.07)', border: '1px solid rgba(255,255,255,0.14)', cursor: 'pointer', fontFamily: SANS, fontWeight: 800, fontSize: 14, color: '#fff' }}>{speed}×</button>
        </div>

        {/* language */}
        <div style={{ marginTop: 18 }}><LangStrip active={lang} onPick={setLang} /></div>
      </div>
    </div>
  );
}
function Ctrl({ icon, onClick }) {
  return <button onClick={onClick} style={{ width: 48, height: 48, borderRadius: 13, background: 'rgba(255,255,255,0.07)', border: '1px solid rgba(255,255,255,0.14)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name={icon} size={22} color="#fff" /></button>;
}

Object.assign(window, { PlaceDetail, AudioPlayer, LangStrip });
