/* global React */
// Partner cards + command palette + tilt logic

const { useState, useEffect, useRef, useMemo, useCallback } = React;

// ----- Tilt wrapper hook -----
function useTilt(strength = 8) {
  const ref = useRef(null);
  const handleMove = useCallback((e) => {
    const el = ref.current; if (!el) return;
    const r = el.getBoundingClientRect();
    const x = (e.clientX - r.left) / r.width - 0.5;
    const y = (e.clientY - r.top) / r.height - 0.5;
    el.style.transform = `perspective(900px) rotateY(${x * strength}deg) rotateX(${-y * strength}deg) translateZ(0)`;
    el.style.setProperty('--mx', `${(x + 0.5) * 100}%`);
    el.style.setProperty('--my', `${(y + 0.5) * 100}%`);
  }, [strength]);
  const handleLeave = useCallback(() => {
    if (ref.current) ref.current.style.transform = '';
  }, []);
  return { ref, onMouseMove: handleMove, onMouseLeave: handleLeave };
}

// ----- Decorative artwork inside featured cards -----
function CardArt({ id, tone }) {
  // each featured gets its own SVG motif
  if (id === 'academy') {
    return (
      <div className="card-art">
        <svg viewBox="0 0 600 380">
          <defs>
            <radialGradient id="kasg" cx="78%" cy="40%" r="60%">
              <stop offset="0%" stopColor="rgba(255,106,61,0.55)" />
              <stop offset="100%" stopColor="rgba(255,106,61,0)" />
            </radialGradient>
          </defs>
          <circle cx="470" cy="150" r="180" fill="url(#kasg)" />
          {/* concentric academy rings */}
          {[40,75,110,150,195,245].map((r,i) => (
            <circle key={i} cx="470" cy="150" r={r} fill="none" stroke="rgba(255,230,200,0.10)" strokeDasharray={i%2 ? "1 4" : "0"} />
          ))}
          {/* hex grid hint */}
          <g stroke="rgba(255,106,61,0.18)" fill="none">
            <polygon points="470,30 540,70 540,150 470,190 400,150 400,70" />
            <polygon points="470,80 510,103 510,143 470,166 430,143 430,103" />
          </g>
          {/* academy nodes */}
          {Array.from({length: 14}).map((_,i) => {
            const a = (i / 14) * Math.PI * 2;
            const r = 200 + (i%3)*18;
            const x = 470 + Math.cos(a)*r;
            const y = 150 + Math.sin(a)*r;
            return <circle key={i} cx={x} cy={y} r="2" fill="rgba(255,106,61,0.7)" />;
          })}
        </svg>
      </div>
    );
  }
  if (id === 'tangem') {
    return (
      <div className="card-art">
        <svg viewBox="0 0 600 380">
          <defs>
            <radialGradient id="tg" cx="75%" cy="50%" r="55%">
              <stop offset="0%" stopColor="rgba(94,235,176,0.35)" />
              <stop offset="100%" stopColor="rgba(94,235,176,0)" />
            </radialGradient>
          </defs>
          <rect width="600" height="380" fill="url(#tg)" />
          {/* stacked cards */}
          <g transform="translate(380,80) rotate(-12)">
            <rect width="180" height="260" rx="14" fill="#0d1410" stroke="rgba(94,235,176,0.4)" />
            <rect x="14" y="14" width="36" height="24" rx="3" fill="rgba(94,235,176,0.5)" />
            <rect x="14" y="220" width="100" height="6" rx="2" fill="rgba(94,235,176,0.3)" />
            <rect x="14" y="232" width="60" height="4" rx="2" fill="rgba(94,235,176,0.18)" />
          </g>
          <g transform="translate(340,60) rotate(-4)">
            <rect width="180" height="260" rx="14" fill="#0a120e" stroke="rgba(94,235,176,0.6)" />
            <rect x="14" y="14" width="36" height="24" rx="3" fill="rgba(94,235,176,0.7)" />
            <g transform="translate(60, 100)">
              <circle r="46" fill="none" stroke="rgba(94,235,176,0.5)" />
              <circle r="20" fill="rgba(94,235,176,0.6)" />
            </g>
            <rect x="14" y="220" width="100" height="6" rx="2" fill="rgba(94,235,176,0.45)" />
            <rect x="14" y="232" width="60" height="4" rx="2" fill="rgba(94,235,176,0.3)" />
          </g>
        </svg>
      </div>
    );
  }
  if (id === 'onekey') {
    return (
      <div className="card-art">
        <svg viewBox="0 0 600 380">
          <defs>
            <radialGradient id="okg" cx="78%" cy="55%" r="55%">
              <stop offset="0%" stopColor="rgba(92,200,255,0.35)" />
              <stop offset="100%" stopColor="rgba(92,200,255,0)" />
            </radialGradient>
          </defs>
          <rect width="600" height="380" fill="url(#okg)" />
          {/* key silhouette in line art */}
          <g stroke="rgba(92,200,255,0.55)" strokeWidth="1.4" fill="none" transform="translate(360,80)">
            <circle cx="80" cy="80" r="60" />
            <circle cx="80" cy="80" r="22" />
            <line x1="138" y1="80" x2="220" y2="80" />
            <line x1="200" y1="80" x2="200" y2="105" />
            <line x1="180" y1="80" x2="180" y2="115" />
          </g>
          {/* circuit traces */}
          <g stroke="rgba(92,200,255,0.18)" fill="none">
            <path d="M60 320 H240 V280 H320" />
            <path d="M60 340 H180 V300 H260" />
            <circle cx="60" cy="320" r="3" fill="rgba(92,200,255,0.6)" />
            <circle cx="320" cy="280" r="3" fill="rgba(92,200,255,0.6)" />
            <circle cx="260" cy="300" r="3" fill="rgba(92,200,255,0.6)" />
          </g>
        </svg>
      </div>
    );
  }
  if (id === 'x') {
    return (
      <div className="card-art">
        <svg viewBox="0 0 600 380">
          {/* big italic "x" */}
          <text x="78%" y="78%" textAnchor="middle" fontFamily="Instrument Serif" fontStyle="italic" fontSize="320" fill="rgba(216,207,193,0.12)">x</text>
          {/* timeline ticks */}
          <g stroke="rgba(216,207,193,0.2)">
            {Array.from({length: 18}).map((_,i) => (
              <line key={i} x1={20 + i*30} y1="350" x2={20 + i*30} y2={340 - (i%4)*8} />
            ))}
          </g>
          <text x="20" y="370" fontFamily="JetBrains Mono" fontSize="9" fill="#6d6358" letterSpacing="2">// MAIN CHANNEL</text>
        </svg>
      </div>
    );
  }
  return null;
}

function LogoMark({ item, className = '' }) {
  return (
    <span className={"logo-mark " + className} aria-hidden="true">
      {item.logo && <img src={item.logo} alt={item.logoAlt || `${item.name} logo`} onError={(e) => { e.currentTarget.remove(); }} />}
      <span>{item.glyph}</span>
    </span>
  );
}

// ----- Card -----
function PartnerCard({ p }) {
  const tilt = useTilt(p.size === 'featured' ? 6 : 8);
  return (
    <a className={"tilt-wrap card " + p.size} data-tone={p.tone}
       href={p.url}
       aria-label={`Open ${p.name}`}
       ref={tilt.ref} onMouseMove={tilt.onMouseMove} onMouseLeave={tilt.onMouseLeave}>
      <div className="card-bg" />
      {p.size === 'featured' && <CardArt id={p.id} tone={p.tone} />}
      <div className="card-veil" />
      <LogoMark item={p} className="card-logo" />
      <div className="card-content">
        <div className="card-top">
          <span className="card-cat">{p.cat}</span>
          <span className="card-status"><span className="pip" />{p.status}</span>
        </div>
        <div>
          <h3 className="card-title">
            {p.name.split(' ').map((w, i, arr) => (
              <React.Fragment key={i}>
                {i === arr.length - 1 ? <em>{w}</em> : w}
                {i < arr.length - 1 ? ' ' : ''}
              </React.Fragment>
            ))}
          </h3>
          {p.desc && <p className="card-desc">{p.desc}</p>}
          <div className="card-meta">
            <span className="tag">{p.tag}</span>
            <span className="open">Open <span className="arr">↗</span></span>
          </div>
        </div>
      </div>
    </a>
  );
}

// ----- Command Palette -----
function CommandPalette({ open, onClose, onSelect, items }) {
  const [q, setQ] = useState('');
  const [active, setActive] = useState(0);
  const inputRef = useRef(null);

  useEffect(() => {
    if (open) {
      setQ(''); setActive(0);
      setTimeout(() => inputRef.current && inputRef.current.focus(), 30);
    }
  }, [open]);

  const filtered = useMemo(() => {
    const term = q.trim().toLowerCase();
    if (!term) return items;
    return items.filter(it =>
      it.name.toLowerCase().includes(term) ||
      it.cat.toLowerCase().includes(term) ||
      it.glyph.toLowerCase().includes(term)
    );
  }, [q, items]);

  useEffect(() => { setActive(0); }, [q]);

  useEffect(() => {
    if (!open) return;
    const onKey = (e) => {
      if (e.key === 'Escape') onClose();
      if (e.key === 'ArrowDown') { e.preventDefault(); setActive(a => Math.min(filtered.length - 1, a + 1)); }
      if (e.key === 'ArrowUp') { e.preventDefault(); setActive(a => Math.max(0, a - 1)); }
      if (e.key === 'Enter') { if (filtered[active]) { onSelect(filtered[active]); } }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, filtered, active, onClose, onSelect]);

  if (!open) return null;

  const groups = {};
  filtered.forEach(it => { groups[it.cat] = groups[it.cat] || []; groups[it.cat].push(it); });

  return (
    <div className="cp-back" onClick={onClose}>
      <div className="cp" onClick={(e) => e.stopPropagation()}>
        <div className="cp-input-wrap">
          <span className="lead">/&gt;</span>
          <input ref={inputRef} className="cp-input" placeholder="search partners, channels, projects…"
                 value={q} onChange={(e) => setQ(e.target.value)} />
          <span className="cp-hint">ESC to close</span>
        </div>
        <div className="cp-list">
          {Object.keys(groups).length === 0 && (
            <div style={{padding:'30px 18px', color:'var(--ink-mute)', fontFamily:'var(--mono)', fontSize:11, letterSpacing:'0.16em', textTransform:'uppercase'}}>// no matches in current orbit</div>
          )}
          {Object.entries(groups).map(([cat, list]) => (
            <div key={cat}>
              <div className="cp-section">// {cat}</div>
              {list.map((it) => {
                const isActive = filtered.indexOf(it) === active;
                return (
                  <div key={it.id} className={"cp-item" + (isActive ? " active" : "")}
                       onMouseEnter={() => setActive(filtered.indexOf(it))}
                       onClick={() => onSelect(it)}>
                    <div className="gly">
                      {it.logo && <img src={it.logo} alt="" onError={(e) => { e.currentTarget.remove(); }} />}
                      <span>{it.glyph}</span>
                    </div>
                    <div className="nm">
                      {it.name}
                      <div className="sub">{it.tag} · {it.status}</div>
                    </div>
                    <div className="go">Open ↗</div>
                  </div>
                );
              })}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

window.PartnerCard = PartnerCard;
window.CommandPalette = CommandPalette;
window.useTilt = useTilt;
