// DramaScope — feature components: social login, library status, reviews, share, ads, notifications, premium, AI quick picks
const { useState, useEffect, useRef } = React;

// ── ICONS (lightweight Lucide-style SVGs) ─────────────────────────────────────
const Icon = ({ name, size=16, color='currentColor', stroke=2 }) => {
  const paths = {
    sparkles: 'M12 3l1.5 4.5L18 9l-4.5 1.5L12 15l-1.5-4.5L6 9l4.5-1.5L12 3zM19 14l.7 2.1L22 17l-2.3.9L19 20l-.7-2.1L16 17l2.3-.9L19 14zM5 14l.7 2.1L8 17l-2.3.9L5 20l-.7-2.1L2 17l2.3-.9L5 14z',
    bookmark: 'M6 3h12v18l-6-4-6 4V3z',
    share:    'M16 6l-4-4-4 4M12 2v14M5 12v8a2 2 0 002 2h10a2 2 0 002-2v-8',
    bell:     'M6 8a6 6 0 0112 0c0 7 3 9 3 9H3s3-2 3-9M10 21a2 2 0 004 0',
    crown:    'M2 18h20l-2-10-5 4-5-7-5 7-5-4-2 10z',
    flame:    'M12 22c5 0 8-3 8-8 0-4-3-7-4-9 0 3-3 5-5 5-1 2-3 4-3 7s2 5 4 5z',
    eye:      'M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12zM12 9a3 3 0 100 6 3 3 0 000-6z',
    eyeOff:   'M2 2l20 20M6.7 6.7C4.1 8.4 2 12 2 12s4 7 10 7c2 0 3.8-.6 5.3-1.5M9.5 9.5a3 3 0 004 4',
    star:     'M12 2l3 7 7 .5-5.5 4.5 2 7L12 17l-6.5 4 2-7L2 9.5 9 9z',
    heart:    'M12 21s-7-4.5-9.5-9C1 8.5 3 5 6.5 5 9 5 11 7 12 8c1-1 3-3 5.5-3 3.5 0 5.5 3.5 4 7C19 16.5 12 21 12 21z',
    msg:      'M3 8a3 3 0 013-3h12a3 3 0 013 3v8a3 3 0 01-3 3H9l-4 4v-4H6a3 3 0 01-3-3V8z',
    users:    'M16 21v-2a4 4 0 00-4-4H6a4 4 0 00-4 4v2M9 11a4 4 0 100-8 4 4 0 000 8zM22 21v-2a4 4 0 00-3-3.9M16 3.1A4 4 0 0116 11',
    play:     'M5 3l14 9-14 9V3z',
    check:    'M5 12l5 5 9-11',
  };
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth={stroke} strokeLinecap="round" strokeLinejoin="round" style={{ display:'inline-block', verticalAlign:'middle' }}>
      <path d={paths[name] || paths.star}/>
    </svg>
  );
};

// ── SOCIAL LOGIN BUTTONS ──────────────────────────────────────────────────────
const SOCIAL_PROVIDERS = [
  { id:'google',   label:'Continue with Google',   color:'#fff',     bg:'#fff',     fg:'#111',   icon:(<svg width="16" height="16" viewBox="0 0 48 48"><path fill="#FFC107" d="M43.6 20.1H42V20H24v8h11.3c-1.6 4.5-6 7.7-11.3 7.7-6.6 0-12-5.4-12-12s5.4-12 12-12c3 0 5.8 1.1 7.9 3l5.7-5.7C34.5 6.1 29.5 4 24 4 12.9 4 4 12.9 4 24s8.9 20 20 20 20-8.9 20-20c0-1.3-.1-2.6-.4-3.9z"/><path fill="#FF3D00" d="M6.3 14.7l6.6 4.8C14.6 16 19 13 24 13c3 0 5.8 1.1 7.9 3l5.7-5.7C34.5 6.1 29.5 4 24 4 16.3 4 9.7 8.3 6.3 14.7z"/><path fill="#4CAF50" d="M24 44c5.4 0 10.3-2.1 14-5.4l-6.5-5.5c-2 1.5-4.6 2.4-7.5 2.4-5.3 0-9.7-3.2-11.3-7.7l-6.5 5C9.4 39.6 16.1 44 24 44z"/><path fill="#1976D2" d="M43.6 20.1H42V20H24v8h11.3c-.8 2.2-2.2 4.2-4.1 5.6l6.5 5.5C42.8 35 44 29.9 44 24c0-1.3-.1-2.6-.4-3.9z"/></svg>) },
  { id:'apple',    label:'Continue with Apple',    color:'#fff',     bg:'#000',     fg:'#fff',   icon:(<svg width="16" height="16" viewBox="0 0 24 24" fill="#fff"><path d="M17.05 12.04c.03 3.18 2.79 4.24 2.82 4.25-.02.07-.43 1.5-1.43 2.96-.86 1.27-1.76 2.53-3.17 2.55-1.39.03-1.84-.83-3.43-.83-1.59 0-2.08.8-3.4.85-1.36.05-2.4-1.37-3.27-2.63C3.55 16.6 2.18 11.83 4 8.61c.9-1.6 2.51-2.61 4.26-2.64 1.34-.03 2.6.9 3.43.9.82 0 2.36-1.11 3.97-.95.68.03 2.58.27 3.81 2.06-.1.06-2.27 1.32-2.42 3.96zM14.59 4.34C15.32 3.46 15.81 2.25 15.67 1c-1.05.04-2.32.7-3.07 1.58-.68.78-1.27 2.02-1.11 3.2 1.17.09 2.36-.59 3.1-1.44z"/></svg>) },
  { id:'facebook', label:'Continue with Facebook', color:'#fff',     bg:'#1877F2', fg:'#fff',   icon:(<svg width="16" height="16" viewBox="0 0 24 24" fill="#fff"><path d="M22 12.06C22 6.5 17.5 2 12 2S2 6.5 2 12.06c0 5 3.66 9.13 8.44 9.88V14.9H7.9v-2.84h2.54v-2.16c0-2.5 1.5-3.9 3.78-3.9 1.1 0 2.24.2 2.24.2v2.46h-1.27c-1.25 0-1.64.77-1.64 1.56v1.84h2.78l-.44 2.84h-2.34V22c4.78-.75 8.45-4.88 8.45-9.94z"/></svg>) },
  { id:'discord',  label:'Continue with Discord',  color:'#fff',     bg:'#5865F2', fg:'#fff',   icon:(<svg width="16" height="16" viewBox="0 0 24 24" fill="#fff"><path d="M19.27 5.33A18.06 18.06 0 0014.78 4l-.21.3a15 15 0 014 2 13.6 13.6 0 00-13.14 0 15 15 0 014.1-2.04L9.32 4a17.95 17.95 0 00-4.5 1.33C2.05 9.49 1.3 13.55 1.67 17.55c1.83 1.36 3.6 2.18 5.34 2.72.43-.59.81-1.21 1.13-1.86-.62-.23-1.21-.51-1.78-.85.15-.11.3-.22.43-.34a12.93 12.93 0 0010.4 0c.14.12.28.23.43.34-.57.34-1.16.62-1.78.85.32.65.7 1.27 1.13 1.86 1.74-.54 3.51-1.36 5.34-2.72.42-4.65-.71-8.67-3-12.22zM8.52 15.31c-1.06 0-1.94-.97-1.94-2.15s.86-2.15 1.94-2.15c1.07 0 1.95.97 1.94 2.15 0 1.18-.86 2.15-1.94 2.15zm7 0c-1.07 0-1.95-.97-1.95-2.15s.86-2.15 1.95-2.15c1.07 0 1.94.97 1.94 2.15 0 1.18-.86 2.15-1.94 2.15z"/></svg>) },
  { id:'x',        label:'Continue with X',        color:'#fff',     bg:'#000',     fg:'#fff',   icon:(<svg width="14" height="14" viewBox="0 0 24 24" fill="#fff"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zM17.083 19.77h1.833L7.084 4.126H5.117z"/></svg>) },
];

function SocialLoginButtons({ onSelect }) {
  return (
    <div style={{ display:'flex', flexDirection:'column', gap:8, marginBottom:18 }}>
      {SOCIAL_PROVIDERS.map(p => (
        <button key={p.id} onClick={()=>onSelect(p)} type="button" style={{
          width:'100%', padding:'10px 14px', borderRadius:8,
          background:p.bg, color:p.fg, border: p.bg==='#fff' ? '1px solid #d0d0d0' : 'none',
          fontWeight:600, fontSize:13.5, display:'flex', alignItems:'center', justifyContent:'center', gap:10,
          transition:'transform 0.1s, filter 0.1s'
        }}
        onMouseEnter={e=>e.currentTarget.style.filter='brightness(1.08)'}
        onMouseLeave={e=>e.currentTarget.style.filter='none'}
        >
          {p.icon}
          <span>{p.label}</span>
        </button>
      ))}
    </div>
  );
}

// ── LIBRARY STATUS ────────────────────────────────────────────────────────────
const LIBRARY_STATUSES = [
  { id:'watching',     label:'Watching',     emoji:'👀', color:'#4a9eff' },
  { id:'plan',         label:'Plan to Watch',emoji:'📌', color:'#7bc3ff' },
  { id:'completed',    label:'Completed',    emoji:'✅', color:'#3dd68c' },
  { id:'favorite',     label:'Favorites',    emoji:'❤️', color:'#ff6b6b' },
  { id:'rewatch',      label:'Rewatch',      emoji:'🔁', color:'#c084fc' },
  { id:'dropped',      label:'Dropped',      emoji:'⛔', color:'#888' },
];

function LibraryStatusButton({ item, fullWidth }) {
  const { user, openSignUp } = window.useAuth();
  const { t } = window.useI18n();
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  const storageKey = `ds_library_${user?.email||'guest'}`;
  const [library, setLibrary] = useState(()=>{ try { return JSON.parse(localStorage.getItem(storageKey))||[]; } catch { return []; }});
  const entry = library.find(x=>x.id===item.id);
  const status = entry?.status;
  const curStatus = LIBRARY_STATUSES.find(s=>s.id===status);

  useEffect(()=>{
    const h = (e)=>{ if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', h);
    return ()=>document.removeEventListener('mousedown', h);
  },[]);

  const setStatus = (newStatus) => {
    if (!user) { openSignUp(); return; }
    let next;
    if (newStatus === null) {
      next = library.filter(x=>x.id!==item.id);
    } else {
      const data = { id:item.id, title_en:item.title_en, title_ru:item.title_ru, title_original:item.title_original, posterPath:item.posterPath, firstAirDate:item.firstAirDate, voteAverage:item.voteAverage, originCountry:item.originCountry, status:newStatus, addedAt:new Date().toISOString() };
      next = entry ? library.map(x=>x.id===item.id?{...x, ...data}:x) : [...library, data];
    }
    setLibrary(next);
    localStorage.setItem(storageKey, JSON.stringify(next));
    window.dispatchEvent(new CustomEvent('ds-library-changed'));
    setOpen(false);
  };

  if (!user) {
    return (
      <button onClick={openSignUp} style={{
        padding:'10px 18px', borderRadius:8, fontSize:13, fontWeight:600,
        background:'var(--bg3)', color:'var(--text2)', border:'1px solid rgba(74,158,255,0.15)',
        display:'flex', alignItems:'center', gap:6, width:fullWidth?'100%':'auto'
      }}>🔒 {t('Add to Watchlist')||'Add to Watchlist'}</button>
    );
  }

  return (
    <div ref={ref} style={{ position:'relative', display:fullWidth?'block':'inline-block', width:fullWidth?'100%':'auto' }}>
      <button onClick={()=>setOpen(v=>!v)} style={{
        padding:'10px 18px', borderRadius:8, fontSize:13, fontWeight:700,
        background: curStatus ? `${curStatus.color}22` : 'var(--accent)',
        color: curStatus ? curStatus.color : '#fff',
        border: curStatus ? `1px solid ${curStatus.color}55` : 'none',
        display:'flex', alignItems:'center', gap:8, width:fullWidth?'100%':'auto',
        justifyContent: fullWidth ? 'space-between' : 'flex-start'
      }}>
        <span style={{ display:'flex', alignItems:'center', gap:6 }}>
          <span>{curStatus ? curStatus.emoji : '+'}</span>
          <span>{curStatus ? curStatus.label : 'Add to Library'}</span>
        </span>
        <span style={{ fontSize:9 }}>▾</span>
      </button>
      {open && (
        <div style={{
          position:'absolute', top:'calc(100% + 6px)', left:0, zIndex:50,
          background:'var(--bg2)', border:'1px solid var(--border)', borderRadius:10,
          padding:6, minWidth:200, boxShadow:'0 8px 28px rgba(0,0,0,0.55)'
        }}>
          {LIBRARY_STATUSES.map(s => (
            <button key={s.id} onClick={()=>setStatus(s.id)} style={{
              width:'100%', padding:'8px 12px', borderRadius:6, fontSize:13, textAlign:'left',
              display:'flex', alignItems:'center', gap:8, color: status===s.id ? s.color : 'var(--text2)',
              background: status===s.id ? `${s.color}18` : 'transparent', marginBottom:2
            }}
            onMouseEnter={e=>{ if(status!==s.id) e.currentTarget.style.background='rgba(74,158,255,0.06)'; }}
            onMouseLeave={e=>{ if(status!==s.id) e.currentTarget.style.background='transparent'; }}
            >
              <span style={{ fontSize:14 }}>{s.emoji}</span>
              <span style={{ fontWeight:status===s.id?700:500 }}>{s.label}</span>
            </button>
          ))}
          {status && (
            <>
              <div style={{ height:1, background:'rgba(74,158,255,0.08)', margin:'4px 8px' }}/>
              <button onClick={()=>setStatus(null)} style={{
                width:'100%', padding:'8px 12px', borderRadius:6, fontSize:13, textAlign:'left',
                color:'var(--red)'
              }}>Remove from Library</button>
            </>
          )}
        </div>
      )}
    </div>
  );
}

// ── RECOMMEND BLOCK ───────────────────────────────────────────────────────────
const RECOMMEND_REASONS = ['Chemistry','Emotional story','Green flag male lead','Amazing OST','Beautiful cinematography','Addictive','Comfort drama','Strong acting','Beautiful romance','Great ending'];

function RecommendBlock({ dramaId }) {
  const { user, openSignIn } = window.useAuth();
  const storageKey = `ds_recommend_${dramaId}_${user?.email||'guest'}`;
  const aggregateKey = `ds_recommend_agg_${dramaId}`;
  const [data, setData] = useState(()=>{ try{ return JSON.parse(localStorage.getItem(storageKey))||{ recommended:false, reasons:[] }; }catch{ return { recommended:false, reasons:[] }; } });
  const [showReasons, setShowReasons] = useState(false);
  const agg = JSON.parse(localStorage.getItem(aggregateKey) || '{"yes":0,"no":0,"total":0}');
  const percent = agg.total > 0 ? Math.round((agg.yes / agg.total) * 100) : Math.floor(Math.random()*30+60);

  const toggleRecommend = () => {
    if (!user) { openSignIn(); return; }
    const next = { ...data, recommended: !data.recommended };
    setData(next);
    localStorage.setItem(storageKey, JSON.stringify(next));
    // simulate aggregate update
    const a = JSON.parse(localStorage.getItem(aggregateKey)||'{"yes":0,"no":0,"total":0}');
    if (next.recommended) { a.yes += 1; a.total += 1; }
    else { a.yes = Math.max(0, a.yes - 1); a.total = Math.max(0, a.total - 1); }
    localStorage.setItem(aggregateKey, JSON.stringify(a));
    if (next.recommended) setShowReasons(true);
  };

  const toggleReason = (r) => {
    const reasons = data.reasons.includes(r) ? data.reasons.filter(x=>x!==r) : [...data.reasons, r];
    const next = { ...data, reasons };
    setData(next);
    localStorage.setItem(storageKey, JSON.stringify(next));
  };

  return (
    <div style={{ background:'var(--bg2)', border:'1px solid var(--border)', borderRadius:12, padding:22, marginTop:16 }}>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:14, flexWrap:'wrap', gap:8 }}>
        <h3 style={{ fontSize:16, fontWeight:700 }}>Recommend this drama</h3>
        <span style={{ fontSize:12, color:'var(--accent2)', fontWeight:600 }}>✅ Recommended by {percent}% of users</span>
      </div>
      <button onClick={toggleRecommend} style={{
        padding:'10px 18px', borderRadius:8, fontSize:13, fontWeight:700,
        background: data.recommended ? 'rgba(61,214,140,0.15)' : 'var(--bg3)',
        color: data.recommended ? 'var(--green)' : 'var(--text2)',
        border: `1px solid ${data.recommended ? 'rgba(61,214,140,0.4)' : 'rgba(74,158,255,0.1)'}`,
        display:'flex', alignItems:'center', gap:8
      }}>
        <Icon name="check" size={14}/>
        {data.recommended ? "You recommend this drama" : "I recommend this drama"}
      </button>

      {data.recommended && (
        <div style={{ marginTop:16 }}>
          <div style={{ fontSize:12, color:'var(--text3)', marginBottom:10, fontWeight:600 }}>Why do you recommend it? (pick all that apply)</div>
          <div style={{ display:'flex', flexWrap:'wrap', gap:6 }}>
            {RECOMMEND_REASONS.map(r => {
              const active = data.reasons.includes(r);
              return (
                <button key={r} onClick={()=>toggleReason(r)} style={{
                  padding:'6px 12px', borderRadius:16, fontSize:11.5, fontWeight:600,
                  background: active ? 'var(--green)' : 'var(--bg3)',
                  color: active ? '#082017' : 'var(--text2)',
                  border:`1px solid ${active?'var(--green)':'rgba(74,158,255,0.1)'}`,
                  transition:'all 0.15s'
                }}>{r}</button>
              );
            })}
          </div>
          <div style={{ marginTop:14, padding:'10px 14px', background:'rgba(61,214,140,0.05)', borderRadius:8, borderLeft:'3px solid var(--green)' }}>
            <div style={{ fontSize:11, color:'var(--text3)', marginBottom:3 }}>Public summary</div>
            <div style={{ fontSize:12, color:'var(--text)' }}>Most recommended for: <strong>Chemistry, Emotional impact, Visuals, OST, Comfort.</strong></div>
          </div>
        </div>
      )}
    </div>
  );
}

// ── REVIEWS SECTION ───────────────────────────────────────────────────────────
const REVIEW_REACTIONS = ['❤️','😂','😭','🔥','🛐','👏','🤯','😡'];

function ReviewsSection({ dramaId }) {
  const { user, openSignIn } = window.useAuth();
  const storageKey = `ds_reviews_${dramaId}`;
  const [reviews, setReviews] = useState(()=>{ try { return JSON.parse(localStorage.getItem(storageKey))||[]; } catch { return []; }});
  const [showForm, setShowForm] = useState(false);
  const [text, setText] = useState('');
  const [isSpoiler, setIsSpoiler] = useState(false);

  const save = (next) => { setReviews(next); localStorage.setItem(storageKey, JSON.stringify(next)); };

  const post = () => {
    if (!user || !text.trim()) return;
    const review = { id:Date.now(), userEmail:user.email, userName:user.name, text:text.trim(), spoiler:isSpoiler, date:'just now', reactions:{}, replies:[] };
    save([review, ...reviews]);
    setText(''); setIsSpoiler(false); setShowForm(false);
  };

  const react = (reviewId, emoji) => {
    if (!user) { openSignIn(); return; }
    save(reviews.map(r => {
      if (r.id!==reviewId) return r;
      const rxs = { ...(r.reactions||{}) };
      const list = rxs[emoji] || [];
      rxs[emoji] = list.includes(user.email) ? list.filter(e=>e!==user.email) : [...list, user.email];
      return { ...r, reactions: rxs };
    }));
  };

  const reply = (reviewId, replyText) => {
    if (!user || !replyText.trim()) return;
    save(reviews.map(r => r.id===reviewId ? { ...r, replies:[...(r.replies||[]), { id:Date.now(), userEmail:user.email, userName:user.name, text:replyText.trim(), date:'just now', reactions:{} }] } : r));
  };

  const removeReview = (reviewId) => save(reviews.filter(r=>r.id!==reviewId));

  return (
    <div style={{ background:'var(--bg2)', border:'1px solid var(--border)', borderRadius:12, padding:22, marginTop:16 }}>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:16, flexWrap:'wrap', gap:8 }}>
        <h3 style={{ fontSize:16, fontWeight:700 }}>Reviews ({reviews.length})</h3>
        {user ? (
          <button onClick={()=>setShowForm(v=>!v)} style={{
            padding:'8px 16px', borderRadius:8, background:'var(--accent)', color:'#fff', fontWeight:700, fontSize:12.5
          }}>{showForm ? 'Cancel' : '+ Write Review'}</button>
        ) : (
          <button onClick={openSignIn} style={{
            padding:'8px 16px', borderRadius:8, background:'var(--bg3)', color:'var(--text2)', fontWeight:600, fontSize:12.5,
            border:'1px solid rgba(74,158,255,0.15)'
          }}>🔒 Sign in to write a review</button>
        )}
      </div>

      {showForm && user && (
        <div style={{ background:'var(--bg3)', border:'1px solid var(--border)', borderRadius:10, padding:16, marginBottom:18 }}>
          <textarea value={text} onChange={e=>setText(e.target.value)} placeholder="Share your thoughts on this drama..." rows={4}
            style={{ width:'100%', padding:'10px 12px', borderRadius:8, background:'var(--bg)', border:'1px solid rgba(74,158,255,0.1)', color:'var(--text)', fontSize:13, outline:'none', resize:'vertical', marginBottom:10 }}/>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', flexWrap:'wrap', gap:8 }}>
            <label style={{ display:'flex', alignItems:'center', gap:6, fontSize:12, color:'var(--text2)', cursor:'pointer' }}>
              <input type="checkbox" checked={isSpoiler} onChange={e=>setIsSpoiler(e.target.checked)}/>
              <Icon name="eyeOff" size={13}/>
              <span>Contains spoilers</span>
            </label>
            <button onClick={post} disabled={!text.trim()} style={{
              padding:'8px 22px', borderRadius:8, background:'var(--accent)', color:'#fff', fontWeight:700, fontSize:13, opacity:!text.trim()?0.5:1
            }}>Post Review</button>
          </div>
        </div>
      )}

      {reviews.length === 0 ? (
        <div style={{ textAlign:'center', padding:'24px 0', color:'var(--text3)', fontSize:13 }}>No reviews yet. Be the first to share your thoughts!</div>
      ) : (
        <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
          {reviews.map(r => <ReviewItem key={r.id} review={r} onReact={react} onReply={reply} onRemove={removeReview} currentUser={user}/>)}
        </div>
      )}
    </div>
  );
}

function ReviewItem({ review:r, onReact, onReply, onRemove, currentUser }) {
  const [revealed, setRevealed] = useState(!r.spoiler);
  const [replyOpen, setReplyOpen] = useState(false);
  const [replyText, setReplyText] = useState('');
  const isOwn = currentUser?.email === r.userEmail;

  return (
    <div style={{ background:'var(--bg3)', border:'1px solid rgba(74,158,255,0.07)', borderRadius:10, padding:16 }}>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:8 }}>
        <div style={{ display:'flex', alignItems:'center', gap:8 }}>
          <div style={{ width:30, height:30, borderRadius:'50%', background:'linear-gradient(135deg, var(--accent), var(--purple))', color:'#fff', fontWeight:700, display:'flex', alignItems:'center', justifyContent:'center', fontSize:12 }}>
            {(r.userName||'?').charAt(0).toUpperCase()}
          </div>
          <div>
            <div style={{ fontSize:12.5, fontWeight:700, color:'var(--accent2)' }}>{r.userName}</div>
            <div style={{ fontSize:10, color:'var(--text3)' }}>{r.date}</div>
          </div>
        </div>
        {isOwn && (
          <button onClick={()=>{ if(window.confirm('Delete this review?')) onRemove(r.id); }} style={{ fontSize:11, color:'var(--text3)' }}>Delete</button>
        )}
      </div>

      {r.spoiler && !revealed ? (
        <div style={{ background:'rgba(255,107,107,0.08)', border:'1px dashed rgba(255,107,107,0.3)', borderRadius:8, padding:14, textAlign:'center' }}>
          <div style={{ fontSize:12, color:'var(--red)', marginBottom:8, display:'flex', alignItems:'center', justifyContent:'center', gap:6 }}>
            <Icon name="eyeOff" size={13}/> Careful — this review contains spoilers
          </div>
          <button onClick={()=>setRevealed(true)} style={{ fontSize:12, color:'var(--accent)', fontWeight:600, padding:'5px 14px', borderRadius:6, background:'rgba(74,158,255,0.1)' }}>
            <Icon name="eye" size={11}/> Show Spoiler
          </button>
        </div>
      ) : (
        <>
          {r.spoiler && (
            <div style={{ fontSize:10, color:'var(--red)', fontWeight:600, marginBottom:8, display:'flex', alignItems:'center', gap:4 }}>
              <Icon name="eyeOff" size={11}/> SPOILER
            </div>
          )}
          <p style={{ fontSize:13.5, lineHeight:1.7, color:'var(--text)', marginBottom:10 }}>{r.text}</p>
        </>
      )}

      <div style={{ display:'flex', gap:4, flexWrap:'wrap', marginTop:10 }}>
        {REVIEW_REACTIONS.map(emoji => {
          const list = (r.reactions||{})[emoji] || [];
          const active = currentUser && list.includes(currentUser.email);
          return (
            <button key={emoji} onClick={()=>onReact(r.id, emoji)} style={{
              padding:'3px 9px', borderRadius:14, fontSize:13,
              background: active ? 'rgba(74,158,255,0.15)' : 'transparent',
              border:`1px solid ${active?'var(--accent)':'rgba(74,158,255,0.08)'}`,
              display:'flex', alignItems:'center', gap:4
            }}>
              <span>{emoji}</span>
              {list.length>0 && <span style={{ fontSize:11, color:'var(--text3)', fontWeight:600 }}>{list.length}</span>}
            </button>
          );
        })}
        {currentUser && (
          <button onClick={()=>setReplyOpen(v=>!v)} style={{
            padding:'3px 9px', borderRadius:14, fontSize:11, color:'var(--text3)', marginLeft:'auto'
          }}>Reply</button>
        )}
      </div>

      {replyOpen && currentUser && (
        <div style={{ marginTop:10, display:'flex', gap:6 }}>
          <input value={replyText} onChange={e=>setReplyText(e.target.value)} placeholder="Write a reply..."
            style={{ flex:1, padding:'7px 11px', borderRadius:7, background:'var(--bg)', border:'1px solid rgba(74,158,255,0.1)', color:'var(--text)', fontSize:12, outline:'none' }}/>
          <button onClick={()=>{ onReply(r.id, replyText); setReplyText(''); setReplyOpen(false); }} disabled={!replyText.trim()} style={{
            padding:'7px 14px', borderRadius:7, background:'var(--accent)', color:'#fff', fontSize:12, fontWeight:600, opacity:!replyText.trim()?0.5:1
          }}>Reply</button>
        </div>
      )}

      {(r.replies||[]).length > 0 && (
        <div style={{ marginTop:12, paddingLeft:14, borderLeft:'2px solid rgba(74,158,255,0.15)', display:'flex', flexDirection:'column', gap:8 }}>
          {r.replies.map(rep => (
            <div key={rep.id} style={{ background:'rgba(74,158,255,0.05)', borderRadius:8, padding:'10px 12px' }}>
              <div style={{ display:'flex', alignItems:'center', gap:6, marginBottom:4 }}>
                <span style={{ fontSize:11.5, fontWeight:700, color:'var(--accent2)' }}>{rep.userName}</span>
                <span style={{ fontSize:10, color:'var(--text3)' }}>· {rep.date}</span>
              </div>
              <p style={{ fontSize:12.5, lineHeight:1.6, color:'var(--text)' }}>{rep.text}</p>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ── SHARE MENU ────────────────────────────────────────────────────────────────
const SHARE_PLATFORMS = [
  { id:'copy',     label:'Copy Link',         color:'#4a9eff' },
  { id:'x',        label:'Share on X',        color:'#000' },
  { id:'facebook', label:'Share on Facebook', color:'#1877F2' },
  { id:'telegram', label:'Share on Telegram', color:'#0088CC' },
  { id:'reddit',   label:'Share on Reddit',   color:'#FF4500' },
  { id:'whatsapp', label:'Share on WhatsApp', color:'#25D366' },
  { id:'pinterest',label:'Share on Pinterest',color:'#E60023' },
];

function ShareMenu({ title='Check this out on DramaScope', url='' }) {
  const [open, setOpen] = useState(false);
  const [copied, setCopied] = useState(false);
  const ref = useRef(null);
  const shareUrl = url || window.location.href;

  useEffect(()=>{
    const h = (e)=>{ if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', h);
    return ()=>document.removeEventListener('mousedown', h);
  },[]);

  const share = (platform) => {
    const encoded = encodeURIComponent(shareUrl);
    const encTitle = encodeURIComponent(title);
    const urls = {
      x: `https://twitter.com/intent/tweet?url=${encoded}&text=${encTitle}`,
      facebook: `https://www.facebook.com/sharer/sharer.php?u=${encoded}`,
      telegram: `https://t.me/share/url?url=${encoded}&text=${encTitle}`,
      reddit:   `https://reddit.com/submit?url=${encoded}&title=${encTitle}`,
      whatsapp: `https://wa.me/?text=${encTitle}%20${encoded}`,
      pinterest:`https://pinterest.com/pin/create/button/?url=${encoded}&description=${encTitle}`,
    };
    if (platform === 'copy') {
      navigator.clipboard?.writeText(shareUrl);
      setCopied(true);
      setTimeout(()=>setCopied(false), 1500);
    } else if (urls[platform]) {
      window.open(urls[platform], '_blank', 'noopener,noreferrer,width=600,height=600');
    }
    setOpen(false);
  };

  return (
    <div ref={ref} style={{ position:'relative', display:'inline-block' }}>
      <button onClick={()=>setOpen(v=>!v)} style={{
        padding:'9px 16px', borderRadius:8, fontSize:13, fontWeight:600,
        background:'var(--bg3)', color:'var(--text)', border:'1px solid rgba(74,158,255,0.15)',
        display:'flex', alignItems:'center', gap:6
      }}>
        <Icon name="share" size={14}/>
        <span>{copied ? 'Copied!' : 'Share'}</span>
      </button>
      {open && (
        <div style={{
          position:'absolute', top:'calc(100% + 6px)', right:0, zIndex:50,
          background:'var(--bg2)', border:'1px solid var(--border)', borderRadius:10,
          padding:6, minWidth:200, boxShadow:'0 8px 28px rgba(0,0,0,0.55)'
        }}>
          {SHARE_PLATFORMS.map(p => (
            <button key={p.id} onClick={()=>share(p.id)} style={{
              width:'100%', padding:'8px 12px', borderRadius:6, fontSize:13, textAlign:'left',
              color:'var(--text2)', display:'flex', alignItems:'center', gap:8, marginBottom:1
            }}
            onMouseEnter={e=>e.currentTarget.style.background='rgba(74,158,255,0.06)'}
            onMouseLeave={e=>e.currentTarget.style.background='transparent'}
            >
              <span style={{ width:6, height:6, borderRadius:'50%', background:p.color, flexShrink:0 }}/>
              <span>{p.label}</span>
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

// ── AD SLOT ───────────────────────────────────────────────────────────────────
function AdSlot({ size='leaderboard', label='Advertisement', style={} }) {
  const sizes = {
    leaderboard: { width:'min(728px,100%)', height:90,  desc:'728×90' },
    billboard:   { width:'min(970px,100%)', height:250, desc:'970×250' },
    mpu:         { width:300, height:250, desc:'300×250' },
    halfpage:    { width:300, height:600, desc:'300×600' },
    mobile:      { width:'min(320px,100%)', height:50,  desc:'320×50'  },
  };
  const s = sizes[size]||sizes.leaderboard;
  return (
    <div style={{ display:'flex', justifyContent:'center', margin:'20px 0', ...style }}>
      <div style={{
        width:s.width, height:s.height, maxWidth:'100%',
        background:'repeating-linear-gradient(45deg, rgba(74,158,255,0.03), rgba(74,158,255,0.03) 8px, rgba(74,158,255,0.06) 8px, rgba(74,158,255,0.06) 16px)',
        border:'1px dashed rgba(74,158,255,0.2)', borderRadius:8,
        display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', gap:4
      }}>
        <span style={{ fontSize:10, color:'var(--text3)', textTransform:'uppercase', letterSpacing:'1.2px', fontWeight:700 }}>{label}</span>
        <span style={{ fontSize:10, color:'var(--text3)', opacity:0.6 }}>{s.desc}</span>
      </div>
    </div>
  );
}

// ── NOTIFICATIONS ─────────────────────────────────────────────────────────────
const SAMPLE_NOTIFICATIONS = [
  { id:1, type:'trailer',  text:'New trailer for "Jade Dragon" just dropped',         time:'2h ago', read:false, emoji:'🎬' },
  { id:2, type:'release',  text:'"Three Lives in Love" releases tomorrow on Youku',   time:'5h ago', read:false, emoji:'📅' },
  { id:3, type:'actor',    text:'Xiao Zhan posted a new update',                       time:'1d ago', read:false, emoji:'⭐' },
  { id:4, type:'reply',    text:'Someone replied to your review of "The Untamed"',    time:'2d ago', read:true,  emoji:'💬' },
  { id:5, type:'episode',  text:'New episode of "Lost You Forever" is available',     time:'3d ago', read:true,  emoji:'▶️' },
];

function NotificationBell() {
  const { user } = window.useAuth();
  const [open, setOpen] = useState(false);
  const [notifications, setNotifications] = useState(SAMPLE_NOTIFICATIONS);
  const ref = useRef(null);
  const unread = notifications.filter(n=>!n.read).length;

  useEffect(()=>{
    const h = (e)=>{ if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', h);
    return ()=>document.removeEventListener('mousedown', h);
  },[]);

  if (!user) return null;

  const markAllRead = () => setNotifications(notifications.map(n=>({...n, read:true})));

  return (
    <div ref={ref} style={{ position:'relative' }}>
      <button onClick={()=>setOpen(v=>!v)} style={{
        padding:'6px 8px', position:'relative', color:'var(--text2)', borderRadius:7,
        border:'1px solid transparent', display:'flex', alignItems:'center'
      }}
      onMouseEnter={e=>e.currentTarget.style.background='rgba(74,158,255,0.07)'}
      onMouseLeave={e=>e.currentTarget.style.background='transparent'}
      >
        <Icon name="bell" size={18}/>
        {unread > 0 && (
          <span style={{
            position:'absolute', top:2, right:2, minWidth:14, height:14, borderRadius:7,
            background:'var(--red)', color:'#fff', fontSize:9, fontWeight:700,
            display:'flex', alignItems:'center', justifyContent:'center', padding:'0 3px'
          }}>{unread}</span>
        )}
      </button>
      {open && (
        <div style={{
          position:'absolute', top:'calc(100% + 8px)', right:0, zIndex:300,
          background:'var(--bg2)', border:'1px solid var(--border)', borderRadius:12,
          padding:10, width:320, maxHeight:420, overflowY:'auto', boxShadow:'0 12px 36px rgba(0,0,0,0.65)'
        }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', padding:'4px 8px 10px', borderBottom:'1px solid rgba(74,158,255,0.08)', marginBottom:6 }}>
            <span style={{ fontSize:13, fontWeight:700 }}>Notifications</span>
            {unread>0 && <button onClick={markAllRead} style={{ fontSize:11, color:'var(--accent)' }}>Mark all read</button>}
          </div>
          {notifications.map(n => (
            <div key={n.id} style={{
              padding:'9px 10px', borderRadius:7, marginBottom:2, cursor:'pointer',
              background: n.read ? 'transparent' : 'rgba(74,158,255,0.06)',
              display:'flex', gap:10, alignItems:'flex-start'
            }}>
              <span style={{ fontSize:18, flexShrink:0 }}>{n.emoji}</span>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontSize:12.5, color:'var(--text)', lineHeight:1.4 }}>{n.text}</div>
                <div style={{ fontSize:10, color:'var(--text3)', marginTop:3 }}>{n.time}</div>
              </div>
              {!n.read && <span style={{ width:6, height:6, borderRadius:'50%', background:'var(--accent)', flexShrink:0, marginTop:6 }}/>}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ── MOOD CHIPS (for AI Picks page) ────────────────────────────────────────────
const MOOD_OPTIONS = [
  { emoji:'😭', label:'Cry'                  },
  { emoji:'❤️', label:'Fall in love'         },
  { emoji:'🔥', label:'Chemistry'            },
  { emoji:'🥺', label:'Comfort'              },
  { emoji:'⚔️', label:'Epic wuxia'           },
  { emoji:'🚩', label:'Toxic romance'        },
  { emoji:'✨', label:'Happy ending'         },
  { emoji:'🌸', label:'Green flag male lead' },
  { emoji:'🎵', label:'Emotional OST'        },
  { emoji:'💪', label:'Strong female lead'   },
];

function MoodChips({ value, onChange }) {
  return (
    <div style={{ display:'flex', flexWrap:'wrap', gap:8, marginBottom:14 }}>
      {MOOD_OPTIONS.map(m => {
        const active = value === m.label;
        return (
          <button key={m.label} onClick={()=>onChange(active ? '' : m.label)} style={{
            padding:'8px 14px', borderRadius:24, fontSize:12.5, fontWeight:600,
            background: active ? 'rgba(192,132,252,0.2)' : 'var(--bg3)',
            color: active ? 'var(--purple)' : 'var(--text2)',
            border:`1px solid ${active?'var(--purple)':'rgba(74,158,255,0.1)'}`,
            display:'flex', alignItems:'center', gap:6, transition:'all 0.15s'
          }}>
            <span>{m.emoji}</span>
            <span>{m.label}</span>
          </button>
        );
      })}
    </div>
  );
}

// ── DRAMA AI QUICK BUTTONS ────────────────────────────────────────────────────
const DRAMA_AI_ACTIONS = [
  { id:'similar',   label:'Similar Dramas',         emoji:'✨' },
  { id:'samevibe',  label:'Same Vibe',              emoji:'🌙' },
  { id:'morelike',  label:'More Like This',         emoji:'💫' },
  { id:'chemistry', label:'Better Chemistry',       emoji:'💞' },
  { id:'damage',    label:'Same Emotional Damage',  emoji:'💔' },
  { id:'comfort',   label:'More Comfort Dramas',    emoji:'🤍' },
  { id:'greenflag', label:'More Green Flag Romance',emoji:'🌿' },
];

function DramaAIButtons({ onAction }) {
  return (
    <div style={{ background:'linear-gradient(135deg, rgba(192,132,252,0.06), rgba(74,158,255,0.03))', border:'1px solid rgba(192,132,252,0.2)', borderRadius:12, padding:18, marginTop:16 }}>
      <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:12 }}>
        <Icon name="sparkles" size={16} color="var(--purple)"/>
        <h3 style={{ fontSize:14, fontWeight:700 }}>AI Recommendations</h3>
      </div>
      <div style={{ display:'flex', flexWrap:'wrap', gap:6 }}>
        {DRAMA_AI_ACTIONS.map(a => (
          <button key={a.id} onClick={()=>onAction && onAction(a)} style={{
            padding:'6px 12px', borderRadius:16, fontSize:11.5, fontWeight:600,
            background:'rgba(192,132,252,0.1)', color:'var(--purple)',
            border:'1px solid rgba(192,132,252,0.2)',
            display:'flex', alignItems:'center', gap:5
          }}
          onMouseEnter={e=>e.currentTarget.style.background='rgba(192,132,252,0.18)'}
          onMouseLeave={e=>e.currentTarget.style.background='rgba(192,132,252,0.1)'}
          >
            <span>{a.emoji}</span>
            <span>{a.label}</span>
          </button>
        ))}
      </div>
    </div>
  );
}

// ── PREMIUM PAGE ──────────────────────────────────────────────────────────────
function PremiumPage() {
  const tiers = [
    { id:'free', name:'Free', price:'€0', period:'forever', highlight:false, features:[
      ['✓','Basic browsing'],['✓','Ratings & reactions'],['✓','News feed'],['✓','Limited AI Picks (5/day)'],['✓','Watchlist'],['×','Ads shown'],['×','Premium badge'],['×','Advanced AI'],
    ]},
    { id:'premium', name:'Premium', price:'€4.99', period:'/month · €39/year', highlight:true, features:[
      ['✓','Everything in Free'],['✓','No ads'],['✓','Premium badge'],['✓','Unlimited AI recommendations'],['✓','Advanced taste profile'],['✓','Unlimited collections'],['✓','Exclusive rankings'],['✓','Priority support'],
    ]},
    { id:'vip', name:'VIP+', price:'€9.99', period:'/month', highlight:false, features:[
      ['✓','Everything in Premium'],['✓','VIP discussions'],['✓','Deeper AI recommendations'],['✓','Profile customization'],['✓','Early access to features'],['✓','VIP-only badges'],['✓','Beta features access'],['✓','Direct creator contact'],
    ]},
  ];

  return (
    <div className="page-enter" style={{ maxWidth:1200, margin:'0 auto', padding:'90px 24px 48px' }}>
      <div style={{ textAlign:'center', marginBottom:36 }}>
        <Icon name="crown" size={36} color="#f5c518"/>
        <h1 style={{ fontSize:32, fontWeight:800, marginTop:10, marginBottom:8 }}>Upgrade Your C-Drama Experience</h1>
        <p style={{ fontSize:14, color:'var(--text2)', maxWidth:520, margin:'0 auto', lineHeight:1.7 }}>
          Go ad-free, unlock advanced AI recommendations, and join the VIP fandom community.
        </p>
      </div>

      <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fit,minmax(260px,1fr))', gap:18, marginBottom:32 }}>
        {tiers.map(t => (
          <div key={t.id} style={{
            background: t.highlight ? 'linear-gradient(135deg, rgba(74,158,255,0.1), rgba(192,132,252,0.08))' : 'var(--bg2)',
            border: t.highlight ? '1.5px solid var(--accent)' : '1px solid var(--border)',
            borderRadius:14, padding:24, position:'relative'
          }}>
            {t.highlight && (
              <div style={{ position:'absolute', top:-10, left:'50%', transform:'translateX(-50%)', background:'var(--accent)', color:'#fff', fontSize:10, fontWeight:800, padding:'4px 12px', borderRadius:12, letterSpacing:'0.5px' }}>MOST POPULAR</div>
            )}
            <h3 style={{ fontSize:18, fontWeight:800, marginBottom:4 }}>{t.name}</h3>
            <div style={{ display:'flex', alignItems:'baseline', gap:6, marginBottom:18 }}>
              <span style={{ fontSize:30, fontWeight:800, color: t.highlight?'var(--accent)':'var(--text)' }}>{t.price}</span>
              <span style={{ fontSize:12, color:'var(--text3)' }}>{t.period}</span>
            </div>
            <button style={{
              width:'100%', padding:'11px', borderRadius:8, marginBottom:18,
              background: t.highlight ? 'var(--accent)' : 'var(--bg3)',
              color: t.highlight ? '#fff' : 'var(--text)', fontWeight:700, fontSize:13,
              border: t.highlight ? 'none' : '1px solid rgba(74,158,255,0.15)'
            }}>
              {t.id==='free' ? 'Current Plan' : t.id==='vip' ? 'Go VIP+' : 'Upgrade to Premium'}
            </button>
            <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
              {t.features.map(([icon, label], i) => (
                <div key={i} style={{ display:'flex', alignItems:'center', gap:8, fontSize:12.5 }}>
                  <span style={{ width:16, color: icon==='✓' ? 'var(--green)' : 'var(--text3)', fontWeight:700 }}>{icon}</span>
                  <span style={{ color: icon==='✓' ? 'var(--text2)' : 'var(--text3)' }}>{label}</span>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>

      <div style={{ textAlign:'center', fontSize:12, color:'var(--text3)' }}>
        Cancel anytime · Secure payment · Premium support
      </div>
    </div>
  );
}

// Export to window
Object.assign(window, {
  Icon, SocialLoginButtons, LibraryStatusButton, RecommendBlock, ReviewsSection,
  ShareMenu, AdSlot, NotificationBell, MoodChips, DramaAIButtons, PremiumPage,
  LIBRARY_STATUSES, RECOMMEND_REASONS, MOOD_OPTIONS,
});
