// app/page-review.jsx — Write a review (working slider, tags, publish).

function RatingSlider({ value, onChange }) {
  const ref = React.useRef(null);
  const setFromX = (clientX) => {
    const el = ref.current; if (!el) return;
    const rect = el.getBoundingClientRect();
    let p = Math.round(((clientX - rect.left) / rect.width) * 100);
    onChange(Math.max(0, Math.min(100, p)));
  };
  const down = (e) => {
    setFromX(e.clientX);
    const move = (ev) => setFromX(ev.clientX);
    const up = () => { window.removeEventListener('pointermove', move); window.removeEventListener('pointerup', up); };
    window.addEventListener('pointermove', move); window.addEventListener('pointerup', up);
  };
  return (
    <div ref={ref} onPointerDown={down} style={{ position: 'relative', height: 8, borderRadius: 999, background: 'var(--paper-3)', border: '1px solid var(--rule)', cursor: 'pointer', touchAction: 'none' }}>
      <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: value + '%', background: 'var(--fan)', borderRadius: 999 }} />
      <div style={{ position: 'absolute', left: value + '%', top: '50%', transform: 'translate(-50%,-50%)', width: 24, height: 24, borderRadius: '50%', background: '#fff', border: '2px solid var(--fan-ink)', boxShadow: '0 2px 6px rgba(40,30,20,.2)' }} />
    </div>
  );
}

function PageReview() {
  const app = useApp();
  const S = window.SCHOLIA;
  const r = S.recording(app.route.id) || S.recording('kleiber-vpo-74');
  const w = r.work;
  const [val, setVal] = React.useState(r.fan);
  const [text, setText] = React.useState('');
  const [tags, setTags] = React.useState({});
  const tagList = ['Reference recording', 'Demonstration sound', 'Brisk tempi', 'Period instruments', 'Live energy', 'Underrated', 'Historic'];
  const toggle = (t) => setTags((s) => ({ ...s, [t]: !s[t] }));
  const chosen = tagList.filter((t) => tags[t]);

  const publish = () => {
    app.addReview(r, { score: val, text: text.trim() || 'Rated ' + val + '.', tags: chosen });
    app.showToast('Review published — thanks for adding your voice');
    navigate('/recording/' + r.id);
  };

  const Field = ({ label, hint, children }) => (
    <section style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
        <h3 className="c-serif" style={{ fontSize: 22, fontWeight: 500, letterSpacing: '-0.01em' }}>{label}</h3>
        {hint && <span className="c-mono" style={{ fontSize: 11.5, color: 'var(--ink-3)' }}>{hint}</span>}
      </div>
      {children}
    </section>
  );

  return (
    <div className="coda" style={{ width: '100%', minHeight: '100%' }}>
      <Nav active="Reviews" />
      <main style={{ maxWidth: 760, margin: '0 auto', padding: '48px 20px 64px', display: 'flex', flexDirection: 'column', gap: 36 }}>
        <header style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          <div className="c-eyebrow clickable" onClick={() => navigate('/recording/' + r.id)}>← Your review</div>
          <h1 className="c-serif" style={{ fontSize: 44, lineHeight: 1, fontWeight: 500, letterSpacing: '-0.02em' }}>Add your voice</h1>
          <p style={{ fontSize: 16, color: 'var(--ink-2)', lineHeight: 1.5 }}>Your rating joins the fan score. Thoughtful, honest takes rise to the top.</p>
        </header>

        {!app.user && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '14px 18px', background: 'var(--paper-2)', border: '1px solid var(--rule)', borderRadius: 4, flexWrap: 'wrap' }}>
            <span style={{ fontSize: 14.5, color: 'var(--ink-2)', flex: 1 }}>You’re posting as a guest. <span className="c-link clickable" onClick={() => navigate('/signin')}>Sign in</span> to publish under your name.</span>
          </div>
        )}

        <div style={{ display: 'flex', alignItems: 'center', gap: 18, padding: 18, background: 'var(--paper-2)', border: '1px solid var(--rule)', borderRadius: 4 }}>
          <Cover composer={r.composerName.toUpperCase().slice(0, 9)} work={(w.subtitle || w.title)[0]} tone={r.tone} size={68} label={r.label.split(' ')[0]} style={{ width: 68, height: 68 }} />
          <div>
            <div className="c-serif" style={{ fontSize: 22, fontWeight: 500 }}>{w.title} {w.subtitle}</div>
            <div style={{ fontSize: 13.5, color: 'var(--ink-2)', marginTop: 3 }}>{r.conductor || r.soloist} · {r.ensemble} · {r.year} · {r.label}</div>
          </div>
          <span className="c-mono c-link clickable" style={{ fontSize: 11.5, letterSpacing: '0.06em', marginLeft: 'auto' }} onClick={() => navigate('/work/' + w.id)}>CHANGE</span>
        </div>

        <Field label="Your score" hint="DRAG TO RATE">
          <div style={{ display: 'flex', alignItems: 'center', gap: 28, padding: '8px 0' }}>
            <Ring value={val} kind="fan" size={92} />
            <div style={{ flex: 1 }}>
              <RatingSlider value={val} onChange={setVal} />
              <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 14 }}>
                <span className="c-mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>0 · SKIP IT</span>
                <span className="c-mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>50 · WORTH HEARING</span>
                <span className="c-mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>100 · ESSENTIAL</span>
              </div>
            </div>
          </div>
        </Field>

        <div style={{ height: 1, background: 'var(--rule)' }} />

        <Field label="Your review" hint={text.length + ' / 2,000'}>
          <textarea value={text} maxLength={2000} onChange={(e) => setText(e.target.value)}
            placeholder="What stands out about this interpretation? Tempo, the orchestral sound, the engineering, how it sits against other accounts you know…"
            style={{ width: '100%', minHeight: 170, resize: 'vertical', border: '1px solid var(--rule-strong)', borderRadius: 4, background: '#fff', padding: '16px 16px', fontFamily: 'var(--serif)', fontSize: 17, lineHeight: 1.5, color: 'var(--ink)', outline: 'none' }} />
        </Field>

        <Field label="Tags" hint="OPTIONAL">
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10 }}>
            {tagList.map((t) => <span key={t} className={'c-chip' + (tags[t] ? ' c-chip--on' : '')} style={{ fontSize: 13.5, padding: '8px 15px' }} onClick={() => toggle(t)}>{t}</span>)}
          </div>
        </Field>

        <div style={{ display: 'flex', alignItems: 'center', gap: 14, paddingTop: 16, borderTop: '1px solid var(--rule)', justifyContent: 'flex-end', flexWrap: 'wrap' }}>
          <span className="c-mono" style={{ fontSize: 11.5, color: 'var(--ink-3)', marginRight: 'auto' }}>Posting as <b style={{ color: 'var(--ink-2)' }}>{app.user ? app.user.handle : '@guest'}</b></span>
          <button className="c-btn c-btn--ghost" onClick={() => { app.showToast('Draft saved'); }}>Save draft</button>
          <button className="c-btn" onClick={publish}>Publish review</button>
        </div>
      </main>
      <Footer />
    </div>
  );
}

Object.assign(window, { PageReview, RatingSlider });
