/* global React */
const { useState: useStateP, useMemo: useMemoP, useEffect: useEffectP, useRef: useRefP } = React;

// ========== PHONE FINDER ==========
// Talks to /api/find — returns real devices + the exact products that have a
// variant for that device. Result links go straight to the product page with
// ?device=<label> so the variant picker is preselected on arrival.
const INR = (n) => '₹' + Number(n || 0).toLocaleString('en-IN');

function PhoneFinder() {
  const [q, setQ] = useStateP('');
  const [devices, setDevices] = useStateP([]); // for chips
  const [matches, setMatches] = useStateP([]); // [{device, products}]
  const [loading, setLoading] = useStateP(false);
  const tRef = useRefP(0);

  // Load device list once for the suggestion chips
  useEffectP(() => {
    fetch('/api/devices').then(r => r.ok ? r.json() : []).then(rows => {
      if (Array.isArray(rows)) setDevices(rows.slice(0, 6));
    }).catch(() => {});
  }, []);

  // Debounced precise search
  useEffectP(() => {
    if (!q.trim()) { setMatches([]); return; }
    setLoading(true);
    clearTimeout(tRef.current);
    tRef.current = setTimeout(() => {
      fetch('/api/find?q=' + encodeURIComponent(q) + '&limit=6')
        .then(r => r.ok ? r.json() : { matches: [] })
        .then(d => setMatches(Array.isArray(d.matches) ? d.matches : []))
        .catch(() => setMatches([]))
        .finally(() => setLoading(false));
    }, 180);
    return () => clearTimeout(tRef.current);
  }, [q]);

  const chips = devices.length
    ? devices.map(d => `${d.brand} ${d.model}`)
    : ['iPhone 15 Pro', 'Galaxy S24 Ultra', 'Pixel 8 Pro', 'OnePlus 12'];

  return (
    <section className="section" id="finder" style={{ background: 'var(--ink)', color: 'var(--cream)', margin: '60px 24px', borderRadius: 4 }}>
      <div className="container">
        <div className="finder-grid" style={{ display: 'grid', gridTemplateColumns: '1fr 1.2fr', gap: 80, alignItems: 'start' }}>
          <div>
            <span className="mono" style={{ color: 'var(--gold)' }}>◆ STEP 01 — FIND YOUR FIT</span>
            <h2 className="display" style={{ fontSize: 'clamp(44px, 7vw, 96px)', margin: '16px 0 24px' }}>
              Type your<br/>phone.
            </h2>
            <p style={{ fontSize: 18, color: 'rgba(245,241,234,0.6)', maxWidth: 420, lineHeight: 1.5 }}>
              We match you to the exact cut — down to the camera hole. Pick your device, jump straight to the product.
            </p>
          </div>
          <div>
            <div style={{ position: 'relative' }}>
              <input
                className="input"
                placeholder="e.g. iPhone 15 Pro, Galaxy S24 Ultra…"
                value={q}
                onChange={e => setQ(e.target.value)}
                style={{ paddingLeft: 60, background: 'rgba(255,255,255,0.06)', color: 'var(--cream)', borderColor: 'rgba(245,241,234,0.2)' }}
              />
              <span style={{ position: 'absolute', left: 22, top: '50%', transform: 'translateY(-50%)', fontSize: 20 }}>🔎</span>
            </div>
            <div style={{ marginTop: 20, display: 'flex', gap: 10, flexWrap: 'wrap' }}>
              {chips.map(s =>
                <button key={s} onClick={() => setQ(s)} className="pill" style={{
                  cursor: 'pointer', border: '1px solid rgba(245,241,234,0.2)',
                  background: 'transparent', color: 'var(--cream)'
                }}>{s}</button>
              )}
            </div>

            {q && (
              <div style={{ marginTop: 24, background: 'rgba(255,255,255,0.04)', borderRadius: 20, padding: 16, border: '1px solid rgba(245,241,234,0.12)', maxHeight: 520, overflowY: 'auto' }}>
                {loading ? (
                  <div style={{ padding: 20, color: 'rgba(245,241,234,0.5)' }}>Searching…</div>
                ) : matches.length === 0 ? (
                  <div style={{ padding: 20, color: 'rgba(245,241,234,0.5)' }}>No match — try "iPhone 15" or "S24 Ultra"</div>
                ) : matches.map(m => (
                  <div key={m.device.id} style={{ marginBottom: 14, paddingBottom: 14, borderBottom: '1px solid rgba(245,241,234,0.08)' }}>
                    <div className="mono" style={{ color: 'var(--gold)', fontSize: 11, letterSpacing: '.12em', marginBottom: 8 }}>
                      ◆ {m.device.label.toUpperCase()} · {m.products.length} {m.products.length === 1 ? 'PRODUCT' : 'PRODUCTS'}
                    </div>
                    {m.products.length === 0 ? (
                      <div style={{ color: 'rgba(245,241,234,0.5)', fontSize: 13 }}>No products listed yet for this device.</div>
                    ) : (
                      <div style={{ display: 'grid', gap: 8 }}>
                        {m.products.slice(0, 6).map(p => (
                          <a key={p.id + '-' + (p.variant_id || 'x')}
                             href={`/products/${p.slug}?device=${encodeURIComponent(m.device.label)}`}
                             style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 8px', borderRadius: 10, color: 'inherit', textDecoration: 'none', transition: 'background 0.15s ease' }}
                             onMouseEnter={e => e.currentTarget.style.background = 'rgba(255,255,255,0.05)'}
                             onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                            {p.image && (
                              <img src={p.image.startsWith('/') || p.image.startsWith('http') ? p.image : '/' + p.image}
                                   alt="" style={{ width: 48, height: 48, objectFit: 'cover', borderRadius: 8, background: '#fff' }} />
                            )}
                            <div style={{ flex: 1, minWidth: 0 }}>
                              <div style={{ fontWeight: 600, fontSize: 15, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{p.name}</div>
                              <div className="mono" style={{ color: 'rgba(245,241,234,0.5)', fontSize: 11, marginTop: 2 }}>
                                {p.cat_group || ''}{p.price ? ' · ' + INR(p.price) : ''}
                              </div>
                            </div>
                            <span style={{ fontSize: 20, color: 'var(--gold)' }}>→</span>
                          </a>
                        ))}
                      </div>
                    )}
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

// ========== DROP TEST VIZ ==========
function DropTest() {
  const [h, setH] = useStateP(2);
  const safe = h <= 3;
  return (
    <section className="section" style={{ background: 'var(--cream-2)' }}>
      <div className="container">
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 60, alignItems: 'center' }}>
          <div>
            <span className="mono" style={{ color: 'var(--muted)' }}>◆ STEP 02 — DURABILITY</span>
            <h2 className="display" style={{ fontSize: 'clamp(56px, 7vw, 96px)', margin: '16px 0 24px' }}>
              Drop it.<br/>
              <span style={{ fontStyle: 'italic' }} className="italic-accent">Seriously.</span>
            </h2>
            <p style={{ fontSize: 18, color: 'var(--muted)', maxWidth: 460, lineHeight: 1.5 }}>
              Drag the slider. Our 9H tempered glass survives up to 3m on tile. Your phone walks away. The glass takes the hit.
            </p>
            <div style={{ marginTop: 32 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 12 }}>
                <span className="mono">DROP HEIGHT</span>
                <span className="display" style={{ fontSize: 28 }}>{h.toFixed(1)}m</span>
              </div>
              <input type="range" min="0.5" max="5" step="0.1" value={h} onChange={e => setH(parseFloat(e.target.value))}
                style={{ width: '100%', accentColor: safe ? 'var(--steel)' : 'var(--gold)' }}/>
              <div style={{ marginTop: 24, padding: 20, borderRadius: 4, background: safe ? 'var(--steel)' : 'var(--gold)', color: safe ? '#fff' : 'var(--ink)' }}>
                <div className="display" style={{ fontSize: 24 }}>
                  {safe ? 'GLASS INTACT · PHONE SAFE' : 'GLASS CRACKED · PHONE SAFE'}
                </div>
                <div className="mono" style={{ marginTop: 6 }}>
                  {safe ? 'No damage. Keep using.' : 'Glass sacrificed itself. Display untouched. Replace with a new LITO.'}
                </div>
              </div>
            </div>
          </div>

          <div style={{ position: 'relative', width: '100%', aspectRatio: '9/14', maxHeight: 560, background: 'var(--cream)', borderRadius: 28, overflow: 'hidden', border: '1px solid var(--line)' }}>
            {/* Ruler */}
            <div style={{ position: 'absolute', left: 16, top: 20, bottom: 96, width: 40 }}>
              {[5, 4, 3, 2, 1, 0].map(m => (
                <div key={m} style={{ position: 'absolute', top: `${(5-m)/5 * 100}%`, transform: 'translateY(-50%)', display: 'flex', alignItems: 'center', gap: 6 }}>
                  <div style={{ width: 12, height: 1, background: 'var(--ink)' }}/>
                  <span className="mono" style={{ fontSize: 10 }}>{m}M</span>
                </div>
              ))}
            </div>
            {/* iPhone silhouette — realistic proportions (~19.5:9, 380×780 at spec scale) */}
            <div style={{
              position: 'absolute',
              top: `${(5 - h) / 5 * 78}%`,
              left: '50%', transform: `translateX(-50%) rotate(${safe ? '6deg' : '18deg'})`,
              width: 'clamp(80px, 22%, 120px)', aspectRatio: '9/19.5',
              borderRadius: 'clamp(14px, 5%, 22px)',
              background: 'linear-gradient(160deg, #1f2a44 0%, var(--ink) 45%, #0e1a36 100%)',
              boxShadow: '0 10px 24px rgba(0,0,0,0.25), inset 0 0 0 2px rgba(255,255,255,0.06)',
              transition: 'top 0.3s ease, transform 0.3s ease',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              padding: '6%'
            }}>
              {/* Screen */}
              <div style={{
                width: '100%', height: '100%',
                borderRadius: 'clamp(8px, 4%, 16px)',
                background: safe ? 'linear-gradient(180deg, #2b82c9 0%, #1e5fa8 100%)' : 'linear-gradient(180deg, #2b82c9 0%, #1e5fa8 100%)',
                position: 'relative', overflow: 'hidden',
                display: 'flex', alignItems: 'center', justifyContent: 'center'
              }}>
                {/* Dynamic island */}
                <div style={{ position: 'absolute', top: '4%', left: '50%', transform: 'translateX(-50%)', width: '36%', height: '7%', borderRadius: 999, background: '#000' }}/>
                {/* Cracks when glass breaks */}
                {!safe && (
                  <svg viewBox="0 0 100 200" preserveAspectRatio="none" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
                    <g stroke="#fff" strokeWidth="1" fill="none" opacity="0.85">
                      <path d="M50 20 L30 60 L44 110 L20 160"/>
                      <path d="M44 110 L70 130 L60 180"/>
                      <path d="M30 60 L10 80"/>
                      <path d="M50 20 L70 50 L90 70"/>
                      <path d="M70 130 L90 150"/>
                    </g>
                  </svg>
                )}
                {/* Emoji reaction */}
                <span style={{ fontSize: 'clamp(18px, 5vw, 28px)', zIndex: 2 }}>{safe ? '😎' : '💥'}</span>
              </div>
            </div>
            {/* Ground */}
            <div style={{
              position: 'absolute', bottom: 0, left: 0, right: 0, height: 72,
              background: 'repeating-linear-gradient(90deg, var(--ink) 0 20px, var(--cream-2) 20px 40px)',
              borderTop: '2px solid var(--ink)'
            }}/>
            <div className="mono" style={{ position: 'absolute', bottom: 14, right: 14, fontSize: 10, color: 'var(--cream)', mixBlendMode: 'difference' }}>TILE · CONCRETE</div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ========== COMPARE ==========
const PROTECTORS = [
  { id: 'clear', name: 'Clear', sub: 'Invisible protection', price: 999, img: 'assets/products/siliicon-edge-clear-glass.jpg', color: 'var(--cream-2)', transparent: false,
    specs: { Clarity: '100%', Privacy: '0°', Matte: 'No', Best: 'Everyday use' } },
  { id: 'privacy', name: 'Privacy', sub: 'Nobody peeks', price: 2098, img: 'assets/privacy-iphone-transparent.png', color: 'var(--ink)', transparent: true,
    specs: { Clarity: '92%', Privacy: '160°', Matte: 'No', Best: 'Commuters · Execs' } },
  { id: 'matte', name: 'Anti-Reflective', sub: 'No glare, no fingerprints', price: 1199, img: 'assets/ar-screen-transparent.png', color: 'var(--gold)', transparent: true,
    specs: { Clarity: '95%', Privacy: '0°', Matte: 'Yes', Best: 'Gamers · Outdoors' } },
];

function Compare() {
  const [sel, setSel] = useStateP('privacy');
  return (
    <section className="section" id="compare">
      <div className="container">
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'end', marginBottom: 48, flexWrap: 'wrap', gap: 20 }}>
          <div>
            <span className="mono" style={{ color: 'var(--muted)' }}>◆ STEP 03 — PICK YOUR FINISH</span>
            <h2 className="display" style={{ fontSize: 'clamp(56px, 7vw, 96px)', margin: '16px 0 0' }}>
              Three finishes.<br/>One glass.
            </h2>
          </div>
          <p style={{ color: 'var(--muted)', maxWidth: 320, fontSize: 16 }}>
            Same 9H core. Different surface. Tap a card to see what changes.
          </p>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 24 }}>
          {PROTECTORS.map((p, i) => {
            const isInk = p.id === 'privacy';
            const selected = sel === p.id;
            return (
            <div key={p.id} onClick={() => setSel(p.id)}
              className="card"
              style={{
                cursor: 'pointer',
                padding: 28,
                position: 'relative',
                outline: selected ? '2px solid var(--ink)' : 'none',
                outlineOffset: 2,
                background: selected ? p.color : '#fff',
                color: selected && isInk ? 'var(--cream)' : 'var(--ink)'
              }}>
              <div className="mono" style={{ color: selected && isInk ? 'rgba(244,242,237,0.6)' : 'var(--muted)' }}>0{i+1} / {p.name.toUpperCase()}</div>
              <h3 className="display" style={{ fontSize: 64, margin: '8px 0 4px' }}>{p.name}</h3>
              <div style={{ opacity: 0.7, fontSize: 14, marginBottom: 20 }}>{p.sub}</div>
              <div style={{ height: 220, display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#fff', borderRadius: 4, marginBottom: 20, boxShadow: 'inset 0 0 0 1px rgba(26,58,107,0.08)' }}>
                <img src={p.img} alt={p.name} style={{
                  maxWidth: '85%',
                  maxHeight: '85%',
                  objectFit: 'contain',
                  mixBlendMode: p.transparent ? 'normal' : 'multiply'
                }}/>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, fontSize: 13, marginBottom: 20 }}>
                {Object.entries(p.specs).map(([k, v]) => (
                  <div key={k}>
                    <div className="mono" style={{ opacity: 0.6 }}>{k}</div>
                    <div style={{ fontWeight: 600 }}>{v}</div>
                  </div>
                ))}
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <div>
                  <span className="display" style={{ fontSize: 32 }}>₹{p.price.toLocaleString('en-IN')}</span>
                  <span style={{ opacity: 0.55, textDecoration: 'line-through', marginLeft: 8, fontSize: 13 }}>₹{Math.round(p.price * 1.3).toLocaleString('en-IN')}</span>
                </div>
                <button className="btn" style={{
                  padding: '10px 18px', fontSize: 12,
                  background: selected && isInk ? 'var(--cream)' : 'var(--ink)',
                  color: selected && isInk ? 'var(--ink)' : 'var(--cream)',
                  borderColor: selected && isInk ? 'var(--cream)' : 'var(--ink)'
                }}>Add →</button>
              </div>
            </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { PhoneFinder, DropTest, Compare, PROTECTORS });
