/* FilterShowcase.jsx — interactive filter sidebar showcase */
(function () {
  'use strict';

  const FDS = {
    bg:'#0f0f0f', panel:'#1a1a1a', surface:'#252525',
    border:'#2e2e2e', border2:'#333333',
    text:'#f5f5f5', dim:'#999999', muted:'#666666',
    accent:'#00FF00',
  };

  const SHOWCASE_FILTERS = [
    { id:'cinematic_blue', name:'Cinematic Blue',  css:'contrast(1.1) saturate(0.85) hue-rotate(195deg) brightness(0.9)' },
    { id:'golden_hour',    name:'Golden Hour',     css:'sepia(0.4) saturate(1.6) brightness(1.08) contrast(1.05)' },
    { id:'vintage_film',   name:'Vintage Film',    css:'sepia(0.35) contrast(0.95) brightness(0.92) saturate(0.8)' },
    { id:'neon_nights',    name:'Neon Nights',     css:'saturate(1.8) contrast(1.2) hue-rotate(270deg) brightness(0.85)' },
    { id:'cyberpunk',      name:'Cyberpunk',       css:'saturate(1.6) hue-rotate(285deg) contrast(1.15) brightness(0.9)' },
    { id:'bw_portrait',    name:'B&W Portrait',    css:'grayscale(1) contrast(1.15) brightness(1.05)' },
    { id:'orange_blue',    name:'Orange & Blue',   css:'saturate(1.3) hue-rotate(10deg) contrast(1.1)' },
    { id:'kodachrome',     name:'Kodachrome',      css:'saturate(1.2) contrast(1.08) brightness(1.02) sepia(0.1)' },
    { id:'dreamy_clouds',  name:'Dreamy Clouds',   css:'brightness(1.12) saturate(0.75) contrast(0.9) blur(0.4px)' },
    { id:'pop_art',        name:'Pop Art',         css:'saturate(2.2) contrast(1.3) hue-rotate(45deg)' },
    { id:'sepia_sunset',   name:'Sepia Sunset',    css:'sepia(0.6) saturate(1.4) brightness(1.05) contrast(1.08)' },
    { id:'bokeh',          name:'Bokeh',           css:'contrast(1.12) brightness(1.05) saturate(1.1)' },
  ];

  const FILTER_CATS = {
    All:       SHOWCASE_FILTERS.map(f => f.id),
    Cinematic: ['cinematic_blue','orange_blue','kodachrome','bw_portrait'],
    Vintage:   ['vintage_film','sepia_sunset','kodachrome'],
    Creative:  ['neon_nights','cyberpunk','pop_art','dreamy_clouds','bokeh'],
    Trending:  ['golden_hour','neon_nights','cinematic_blue','orange_blue'],
  };

  function FilterSceneSVG({ fid, filterCss }) {
    const gid = 'fg' + fid.replace(/_/g,'');
    return (
      <svg viewBox="0 0 100 130" xmlns="http://www.w3.org/2000/svg"
        style={{ width:'100%', height:'100%', display:'block', filter: filterCss || 'none' }}>
        <defs>
          <linearGradient id={gid} x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor="#3a7bd5"/><stop offset="100%" stopColor="#87ceeb"/>
          </linearGradient>
        </defs>
        <rect width="100" height="130" fill={`url(#${gid})`}/>
        <circle cx="74" cy="22" r="10" fill="#ffd700"/>
        <ellipse cx="22" cy="18" rx="13" ry="5" fill="white" opacity="0.9"/>
        <ellipse cx="33" cy="14" rx="9" ry="4" fill="white" opacity="0.85"/>
        <ellipse cx="63" cy="27" rx="11" ry="4" fill="white" opacity="0.7"/>
        <polygon points="0,80 22,44 44,80" fill="#5a7a5a"/>
        <polygon points="28,80 56,33 84,80" fill="#4a6a4a"/>
        <polygon points="62,80 87,50 100,80" fill="#3a5a3a"/>
        <rect y="78" width="100" height="52" fill="#4a7a2a"/>
        <rect x="9" y="54" width="19" height="26" fill="#1a1a2a"/>
        <rect x="11" y="57" width="4" height="4" fill="#ffd700" opacity="0.6"/>
        <rect x="18" y="57" width="4" height="4" fill="#ffd700" opacity="0.4"/>
        <rect x="11" y="64" width="4" height="4" fill="#ffd700" opacity="0.7"/>
        <rect x="47.5" y="68" width="3" height="12" fill="#4a2a0a"/>
        <circle cx="49" cy="62" r="7" fill="#2a5a1a"/>
        <ellipse cx="65" cy="102" rx="22" ry="4" fill="#8a6a3a" opacity="0.5"/>
        <circle cx="65" cy="84" r="2.5" fill="#f5c5a0"/>
        <rect x="63.5" y="86" width="3" height="6" fill="#3a5a8a"/>
      </svg>
    );
  }

  function FilterShowcase({ scale = 1, style = {}, className = '' }) {
    const [cat, setCat]         = React.useState('All');
    const [sel, setSel]         = React.useState(null);
    const [hov, setHov]         = React.useState(null);
    const [favs, setFavs]       = React.useState(new Set());
    const [q, setQ]             = React.useState('');
    const [toast, setToast]     = React.useState(null);
    const [userDid, setUserDid] = React.useState(false);
    const timerRef              = React.useRef(null);
    const idxRef                = React.useRef(0);

    const catIds  = FILTER_CATS[cat] || FILTER_CATS.All;
    const visible = SHOWCASE_FILTERS.filter(f =>
      catIds.includes(f.id) && f.name.toLowerCase().includes(q.toLowerCase())
    );

    React.useEffect(() => {
      if (userDid) return;
      timerRef.current = setInterval(() => {
        if (visible.length === 0) return;
        idxRef.current = (idxRef.current + 1) % visible.length;
        setSel(visible[idxRef.current].id);
      }, 3000);
      return () => clearInterval(timerRef.current);
    }, [userDid, cat, q, visible.length]);

    const interact = () => {
      if (!userDid) { clearInterval(timerRef.current); setUserDid(true); }
    };
    const showToast = msg => {
      setToast(msg);
      setTimeout(() => setToast(null), 2000);
    };
    const toggleFav = (e, id) => {
      e.stopPropagation(); interact();
      setFavs(prev => { const n = new Set(prev); n.has(id) ? n.delete(id) : n.add(id); return n; });
    };

    return (
      <div onMouseDown={interact} className={className}
        style={{
          width:680, height:480,
          background: FDS.bg, border:`1px solid ${FDS.border}`,
          borderRadius:8, overflow:'hidden', display:'flex',
          fontFamily:"'Inter',-apple-system,sans-serif", position:'relative',
          transform: scale !== 1 ? `scale(${scale})` : undefined,
          transformOrigin:'top left',
          ...style,
        }}>

        {/* ── Category rail ── */}
        <div style={{ width:140, background:FDS.panel, borderRight:`1px solid ${FDS.border}`, padding:'14px 0', flexShrink:0 }}>
          <div style={{ padding:'0 14px 10px', fontSize:10, color:FDS.muted, letterSpacing:2, textTransform:'uppercase', fontWeight:600 }}>Categories</div>
          {Object.keys(FILTER_CATS).map(c => {
            const on = cat === c;
            return (
              <div key={c} onClick={() => { setCat(c); interact(); }}
                style={{
                  padding:'8px 14px', cursor:'pointer', fontSize:12,
                  display:'flex', alignItems:'center', gap:7,
                  color: on ? FDS.accent : FDS.dim,
                  background: on ? 'rgba(0,255,0,0.07)' : 'transparent',
                  borderLeft: on ? `2px solid ${FDS.accent}` : '2px solid transparent',
                  transition:'all 0.1s',
                }}>
                <span style={{ width:5, height:5, borderRadius:99, background: on ? FDS.accent : '#555', flexShrink:0 }}/>
                {c}
              </div>
            );
          })}
        </div>

        {/* ── Main panel ── */}
        <div style={{ flex:1, display:'flex', flexDirection:'column', overflow:'hidden', minWidth:0 }}>

          {/* Header */}
          <div style={{ padding:'12px 14px 10px', borderBottom:`1px solid ${FDS.border}`, flexShrink:0 }}>
            <div style={{ fontSize:11, fontWeight:700, color:FDS.text, letterSpacing:2, textTransform:'uppercase', marginBottom:8 }}>
              Video Filters
            </div>
            <input
              value={q} onChange={e => { setQ(e.target.value); interact(); }}
              placeholder="Search filters…"
              style={{
                width:'100%', background:FDS.surface, border:`1px solid ${FDS.border2}`,
                borderRadius:4, color:FDS.text, fontSize:11, padding:'6px 10px',
                outline:'none', boxSizing:'border-box', fontFamily:'inherit',
              }}
            />
          </div>

          {/* Filter grid */}
          <div style={{ flex:1, overflowY:'auto', padding:8, display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:5, alignContent:'start' }}>
            {visible.map(f => {
              const isS = sel === f.id, isH = hov === f.id;
              return (
                <div key={f.id}
                  onClick={() => { setSel(f.id); interact(); }}
                  onMouseEnter={() => setHov(f.id)}
                  onMouseLeave={() => setHov(null)}
                  style={{
                    borderRadius:5, overflow:'hidden', cursor:'pointer',
                    border: isS ? `1px solid ${FDS.accent}` : `1px solid ${isH ? '#555' : FDS.border}`,
                    boxShadow: isS ? `0 0 0 1px ${FDS.accent},0 0 10px rgba(0,255,0,0.25)` : isH ? '0 3px 8px rgba(0,0,0,0.5)' : 'none',
                    transform: isH && !isS ? 'translateY(-1px)' : 'none',
                    transition:'all 0.12s', position:'relative',
                  }}>
                  <div style={{ height:66, overflow:'hidden', position:'relative' }}>
                    <FilterSceneSVG fid={f.id} filterCss={f.css}/>
                    <button onClick={e => toggleFav(e, f.id)}
                      style={{ position:'absolute', top:3, left:3, background:'rgba(0,0,0,0.72)', border:'none', borderRadius:99, width:18, height:18, cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', padding:0, fontSize:10, color: favs.has(f.id) ? '#ff4466' : '#888' }}>
                      {favs.has(f.id) ? '♥' : '♡'}
                    </button>
                    {isS && <div style={{ position:'absolute', top:3, right:3, background:FDS.accent, borderRadius:3, width:15, height:15, display:'flex', alignItems:'center', justifyContent:'center' }}><span style={{ fontSize:9, color:'#000', fontWeight:900 }}>✓</span></div>}
                  </div>
                  <div style={{ padding:'4px 7px', background:FDS.panel }}>
                    <div style={{ fontSize:10, color: isS ? FDS.accent : FDS.text, fontWeight: isS ? 700 : 400, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>
                      {f.name}
                    </div>
                  </div>
                  {isS && (
                    <button onClick={e => { e.stopPropagation(); interact(); showToast('Filter applied to clip ✓'); }}
                      style={{ width:'100%', background:FDS.accent, color:'#000', border:'none', padding:'4px 0', fontSize:10, fontWeight:800, cursor:'pointer', fontFamily:'inherit', letterSpacing:0.5 }}>
                      APPLY
                    </button>
                  )}
                </div>
              );
            })}
            {visible.length === 0 && (
              <div style={{ gridColumn:'1/-1', padding:24, textAlign:'center', color:FDS.muted, fontSize:12 }}>No filters found</div>
            )}
          </div>
        </div>

        {/* Toast */}
        {toast && (
          <div style={{ position:'absolute', bottom:12, left:'50%', transform:'translateX(-50%)', background:FDS.accent, color:'#000', padding:'7px 16px', borderRadius:6, fontSize:11, fontWeight:700, whiteSpace:'nowrap', zIndex:20, boxShadow:'0 0 18px rgba(0,255,0,0.4)', pointerEvents:'none' }}>
            {toast}
          </div>
        )}
      </div>
    );
  }

  window.FilterShowcase = FilterShowcase;
})();
