// Interactive lab: pick a tenant, tweak name + color, preview updates live
const { useState: useStateLab, useRef: useRefLab, useEffect: useEffectLab } = React;

function Lab() {
  const [name, setName] = useStateLab("Lumen");
  const [domain, setDomain] = useStateLab("lumen.crm");
  const [color, setColor] = useStateLab("#007fdc");
  const previewRef = useRefLab(null);

  const tenantTint = hexToTint(color);
  const mark = name.charAt(0).toUpperCase();

  const presets = [
    { name: "Lumen", color: "#007fdc" },
    { name: "Kairo", color: "#10B87A" },
    { name: "Nexa", color: "#8B5CF6" },
    { name: "Orbit", color: "#F59E0B" },
    { name: "Helix", color: "#EF4444" },
    { name: "Zenith", color: "#0EA5E9" },
  ];

  // Tilt on hover
  useEffectLab(() => {
    const el = previewRef.current;
    if (!el) return;
    const onMove = (e) => {
      const r = el.getBoundingClientRect();
      const dx = (e.clientX - r.left - r.width / 2) / r.width;
      const dy = (e.clientY - r.top - r.height / 2) / r.height;
      el.style.transform = `rotateY(${-8 + dx * 10}deg) rotateX(${4 - dy * 8}deg)`;
    };
    const onLeave = () => { el.style.transform = `rotateY(-8deg) rotateX(4deg)`; };
    el.addEventListener('mousemove', onMove);
    el.addEventListener('mouseleave', onLeave);
    return () => { el.removeEventListener('mousemove', onMove); el.removeEventListener('mouseleave', onLeave); };
  }, []);

  return (
    <section className="section" id="lab">
      <div className="container">
        <div className="section-head reveal">
          <span className="eyebrow"><span className="eyebrow-tag">Live</span>Your brand, in 10 seconds</span>
          <h2>The CRM Problem, <em>Solved.</em></h2>
          <p>Ditch the steep learning curves and lead loss. Switch to an AI-powered CRM that is powerful, 100% yours and actually enjoyable to use. Type your brand name below to see your new platform come to life instantly.</p>
        </div>

        <div className="swap-lab reveal" style={{ '--tenant-color': color, '--tenant-tint': tenantTint }}>
          <div className="swap-controls">
            <div>
              <h3>1 · Pick a brand preset</h3>
            </div>
            <div className="brand-picker">
              {presets.map(p => (
                <button
                  key={p.name}
                  className={`brand-chip ${name === p.name ? 'active' : ''}`}
                  style={{ color: p.color }}
                  onClick={() => { setName(p.name); setDomain(`${p.name.toLowerCase()}.crm`); setColor(p.color); }}
                >
                  <span className="swatch"></span>
                  <span style={{ color: 'var(--ink-900)' }}>{p.name}</span>
                </button>
              ))}
            </div>

            <div>
              <h3>2 · Or go custom</h3>
            </div>
            <div className="swap-inputs">
              <div className="input-group">
                <label>Brand name</label>
                <input value={name} onChange={e => setName(e.target.value)} />
              </div>
            </div>
            <div className="input-group" style={{ marginTop: -8 }}>
              <label>Domain</label>
              <input value={domain} onChange={e => setDomain(e.target.value)} />
            </div>

            <div className="input-group">
              <label>Primary color</label>
              <div className="color-picker">
                <input type="color" value={color} onChange={e => setColor(e.target.value)} />
                <div className="hex">{color.toUpperCase()}</div>
              </div>
            </div>

            <div style={{
              padding: 14,
              background: 'white',
              border: '1px dashed var(--line-strong)',
              borderRadius: 10,
              fontSize: 12,
              color: 'var(--ink-500)',
              lineHeight: 1.5
            }}>
              <strong style={{ color: 'var(--ink-900)' }}>Happy with the look?</strong> We'll get your branded CRM live on <span className="mono" style={{ color }}>{domain}</span> with logo, palette, and emails — typically in 14–30 days.
            </div>
          </div>

          <div className="swap-preview">
            <div className="preview-device" ref={previewRef}>
              <div className="preview-topbar">
                <div className="preview-logo">{mark}</div>
                <div className="preview-brand">
                  {name}<span className="dot">.crm</span>
                </div>
                <div className="preview-nav">
                  <span className="on">Dashboard</span>
                  <span>Leads</span>
                  <span>Pages</span>
                </div>
                <div className="preview-actions">
                  <div className="btn-mini" style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', lineHeight: 1 }}>+ New Lead</div>
                </div>
              </div>
              <div className="preview-body-2">
                <div className="stat-bar">
                  <div className="sb-cell"><div className="sb-label">Total</div><div className="sb-val">2,184</div></div>
                  <div className="sb-cell"><div className="sb-label">New</div><div className="sb-val" style={{ color }}>312</div></div>
                  <div className="sb-cell"><div className="sb-label">Contacted</div><div className="sb-val">874</div></div>
                  <div className="sb-cell"><div className="sb-label">Qualified</div><div className="sb-val">496</div></div>
                  <div className="sb-cell"><div className="sb-label">Converted</div><div className="sb-val" style={{ color: '#10B87A' }}>248</div></div>
                  <div className="sb-cell"><div className="sb-label">Lost</div><div className="sb-val" style={{ color: 'var(--ink-300)' }}>254</div></div>
                </div>

                <div className="search-row">
                  <div className="search-input">
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="11" cy="11" r="7" /><path d="m20 20-3-3" /></svg>
                    <span>Search leads, companies, owners…</span>
                  </div>
                  <div className="filter-btn" style={{ borderColor: color, color }}>
                    <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M3 6h18M6 12h12M10 18h4" /></svg>
                    Filter
                  </div>
                </div>

                <div className="leads-table">
                  <div className="lt-head">
                    <div>Name</div><div>Company</div><div>Stage</div><div>Value</div>
                  </div>
                  {[
                    ['Ava Reyes', 'Acme Robotics', 'Qualified', '$12,400', '#10B87A'],
                    ['Noah Patel', 'Forge Labs', 'Contacted', '$8,200', color],
                    ['Mia Chen', 'Northwind Co.', 'New', '$3,900', '#F59E0B'],
                    ['Liam Okafor', 'Vertex Studio', 'Converted', '$24,800', '#10B87A'],
                    ['Sara Müller', 'Helio Systems', 'Qualified', '$15,100', '#10B87A'],
                  ].map((row, i) => (
                    <div className="lt-row" key={i}>
                      <div className="lt-name">
                        <div className="lt-avatar" style={{ background: row[4] }}>{row[0].charAt(0)}</div>
                        {row[0]}
                      </div>
                      <div>{row[1]}</div>
                      <div><span className="lt-pill" style={{ background: `${row[4]}1f`, color: row[4] }}>{row[2]}</span></div>
                      <div className="lt-val">{row[3]}</div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function hexToTint(hex) {
  const c = hex.replace('#', '');
  const r = parseInt(c.slice(0, 2), 16);
  const g = parseInt(c.slice(2, 4), 16);
  const b = parseInt(c.slice(4, 6), 16);
  // blend toward white
  const mix = (v) => Math.round(v + (255 - v) * 0.88);
  return `rgb(${mix(r)}, ${mix(g)}, ${mix(b)})`;
}

window.Lab = Lab;
