// ─────────────────────────────────────────────────────────
//  Playground — Live mini-SaaS sandbox
//  3 tools: theme tokens · XSS sanitizer · n8n payload preview
// ─────────────────────────────────────────────────────────

const { useState: useStateP, useMemo: useMemoP } = React;

const TOKEN_SETS = {
  obsidian: { bg:'#050505', ink:'#F2EFE7', accent:'#00F2FE', muted:'#8A8F98' },
  bone:     { bg:'#F5F1EB', ink:'#16140F', accent:'#0F5132', muted:'#6B6558' },
  noir:     { bg:'#0E0E0C', ink:'#F2EFE7', accent:'#C3FF6A', muted:'#928B7C' },
  ember:    { bg:'#1A0F0A', ink:'#F2E7DF', accent:'#FF7A45', muted:'#9A8A80' },
};

// ── Tab 1: Tokens ─────────────────────────────────────────
function TokensTool() {
  const [active, setActive] = useStateP('obsidian');
  const set = TOKEN_SETS[active];

  return (
    <>
      <span className="kicker" style={{marginBottom:14, display:'inline-flex'}}>§Sandbox · Design tokens</span>
      <h3>Live theme tokens — flip the system in 8 ms.</h3>
      <p className="pg-desc">
        Same component tree, four parallel palettes. The token layer is decoupled from
        the markup, so every brand we ship gets re-skinned without touching a single
        component file.
      </p>

      <div className="swatches">
        {Object.keys(TOKEN_SETS).map(k => {
          const s = TOKEN_SETS[k];
          return (
            <button
              key={k}
              className={`swatch magnetic-trigger ${k === active ? 'active' : ''}`}
              onClick={() => setActive(k)}
              style={{
                background:s.bg, color:s.ink,
                borderColor: k === active ? s.accent : 'var(--line)',
              }}
            >
              <span className="name" style={{color:s.ink}}>{k}</span>
              <div style={{display:'flex', gap:4}}>
                <span style={{width:14, height:14, background:s.accent, borderRadius:4}}/>
                <span style={{width:14, height:14, background:s.muted, borderRadius:4}}/>
              </div>
              <span className="hex" style={{color:s.muted}}>{s.accent}</span>
            </button>
          );
        })}
      </div>

      {/* Live preview */}
      <div style={{
        background:set.bg, color:set.ink,
        border:`1px solid ${set.accent}30`, borderRadius:16, padding:28,
        transition:'all .35s cubic-bezier(.2,.8,.2,1)',
      }}>
        <div style={{
          fontFamily:'var(--mono)', fontSize:10, letterSpacing:'0.18em',
          textTransform:'uppercase', color:set.muted, marginBottom:12,
        }}>
          Preview · {active}
        </div>
        <div style={{
          fontFamily:'var(--serif)', fontSize:42, lineHeight:1.0,
          letterSpacing:'-0.02em',
        }}>
          The same component,{' '}
          <span style={{color:set.accent, fontStyle:'italic'}}>re-themed.</span>
        </div>
        <div style={{
          marginTop:20, display:'inline-flex', gap:10, alignItems:'center',
          padding:'12px 20px', background:set.accent, color:set.bg,
          borderRadius:999, fontSize:14, fontWeight:500,
        }}>
          <span>Primary action</span><span>→</span>
        </div>
      </div>
    </>
  );
}

// ── Tab 2: XSS Sanitizer ──────────────────────────────────
function sanitize(input) {
  // strip script/style tags, on* handlers, javascript: protocol
  const stripped = [];
  let out = input;

  out = out.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, m => {
    stripped.push(m); return '';
  });
  out = out.replace(/<style\b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>/gi, m => {
    stripped.push(m); return '';
  });
  out = out.replace(/\son\w+\s*=\s*"[^"]*"/gi, m => { stripped.push(m); return ''; });
  out = out.replace(/\son\w+\s*=\s*'[^']*'/gi, m => { stripped.push(m); return ''; });
  out = out.replace(/javascript:/gi, m => { stripped.push(m); return ''; });
  out = out.replace(/<iframe\b[^>]*>/gi, m => { stripped.push(m); return ''; });

  // SQL-ish patterns
  out = out.replace(/(\b(union|select|drop|insert|delete)\s+\b)/gi, m => {
    stripped.push(m); return '';
  });

  return { out: out.trim(), removed: stripped };
}

function escapeHTML(s) {
  return s.replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'})[c]);
}

const SAMPLE_PAYLOAD = `Hello — interested in the Series A portfolio audit.
<script>alert('xss')</script>
Contact: <a href="javascript:steal()">click</a>
Budget: $250K. <iframe src="evil"></iframe>
SELECT * FROM clients;`;

function SanitizerTool() {
  const [input, setInput] = useStateP(SAMPLE_PAYLOAD);
  const result = useMemoP(() => sanitize(input), [input]);
  const removed = result.removed.length;

  return (
    <>
      <span className="kicker" style={{marginBottom:14, display:'inline-flex'}}>§Sandbox · Input sanitization</span>
      <h3>Live XSS &amp; injection sanitizer.</h3>
      <p className="pg-desc">
        Type or paste anything — script tags, inline event handlers, <code>javascript:</code> URIs,
        iframes, SQL patterns. Watch them get stripped in real time, before any payload reaches
        the server.
      </p>

      <div className="sanit-grid">
        <div className="sanit-col">
          <label>Raw input · untrusted</label>
          <textarea
            value={input}
            onChange={e => setInput(e.target.value)}
            spellCheck={false}
          />
        </div>
        <div className="sanit-col">
          <label>Sanitized output · safe</label>
          <div className="out">{result.out || <span style={{color:'var(--muted)'}}>(empty)</span>}</div>
        </div>
      </div>

      <div className="sanit-meta">
        <div>Threats stripped: <span>{removed.toString().padStart(2, '0')}</span></div>
        <div>Input length: <span>{input.length}</span></div>
        <div>Output length: <span>{result.out.length}</span></div>
        <div>Status: <span>{removed > 0 ? '⚠ neutralized' : '✓ clean'}</span></div>
      </div>
    </>
  );
}

// ── Tab 3: Payload preview ────────────────────────────────
function PayloadTool() {
  const [form, setForm] = useStateP({
    name: 'Aarav K.',
    email: 'aarav@luxe-estates.in',
    segment: 'Real Estate',
    budget: '50K-100K USD',
  });

  const payload = {
    event: 'webbrandify.lead.captured',
    timestamp: new Date().toISOString(),
    routing: ['crm.hubspot', 'whatsapp.business', 'slack.sales-inbound'],
    actor: {
      name: form.name,
      email: form.email,
    },
    intent: {
      segment: form.segment,
      budget_bracket: form.budget,
      source: 'portfolio.rohit-sharma',
    },
    score: 87,
    next_action: 'route_to_principal',
  };

  // syntax-highlight a JSON string
  const json = JSON.stringify(payload, null, 2);
  const highlighted = json
    .replace(/("(?:[^"\\]|\\.)*?")(\s*:)/g, '<span class="k">$1</span>$2')
    .replace(/:\s*("(?:[^"\\]|\\.)*?")/g, ': <span class="s">$1</span>')
    .replace(/:\s*(\d+)/g, ': <span class="n">$1</span>');

  return (
    <>
      <span className="kicker" style={{marginBottom:14, display:'inline-flex'}}>§Sandbox · n8n webhook</span>
      <h3>Lead → JSON → n8n webhook ingestion.</h3>
      <p className="pg-desc">
        What the lead form on this page emits when a visitor submits. This payload
        shape is exactly what our n8n flow consumes — typed, scored, and routed in
        under 3 seconds.
      </p>

      <div className="payload-wrap">
        <div className="payload-form">
          <label>Lead name</label>
          <input value={form.name} onChange={e => setForm({...form, name:e.target.value})}/>
          <label>Email</label>
          <input value={form.email} onChange={e => setForm({...form, email:e.target.value})}/>
          <label>Segment</label>
          <select value={form.segment} onChange={e => setForm({...form, segment:e.target.value})}>
            <option>Real Estate</option>
            <option>Fashion / D2C</option>
            <option>SaaS / B2B</option>
            <option>Hospitality</option>
          </select>
          <label>Budget bracket</label>
          <select value={form.budget} onChange={e => setForm({...form, budget:e.target.value})}>
            <option>10K-50K USD</option>
            <option>50K-100K USD</option>
            <option>100K-500K USD</option>
            <option>500K+ USD</option>
          </select>
        </div>

        <div className="payload-out">
          <div className="payload-out-head">
            <span>POST /webhook/leads</span>
            <span className="pulse">live</span>
          </div>
          <pre dangerouslySetInnerHTML={{__html: highlighted}}/>
        </div>
      </div>
    </>
  );
}

// ── Composer ──────────────────────────────────────────────
const TABS = [
  { id:'tokens', i:'01', l:'Design tokens',     C: TokensTool },
  { id:'sanit',  i:'02', l:'XSS sanitizer',     C: SanitizerTool },
  { id:'pay',    i:'03', l:'Webhook payload',   C: PayloadTool },
];

function Playground() {
  const [active, setActive] = useStateP('tokens');
  const Tool = TABS.find(t => t.id === active).C;

  return (
    <section className="section shell" data-screen-label="Sandbox">
      <div>
        <div className="kicker">§03 · Live proof, not a portfolio</div>
        <h2 style={{
          fontFamily:'var(--serif)', fontWeight:400,
          fontSize:'clamp(40px, 5vw, 76px)', lineHeight:1.0,
          letterSpacing:'-0.02em', margin:'18px 0 0', maxWidth:'20ch',
          textWrap:'balance',
        }}>
          A working sandbox.<br/>
          <span style={{fontStyle:'italic', color:'var(--accent)'}}>Press anything.</span>
        </h2>
      </div>

      <div className="playground">
        <div className="pg-head">
          <span className="pg-dot r"/><span className="pg-dot y"/><span className="pg-dot g"/>
          <div className="pg-title">studio.webbrandify.com / sandbox</div>
          <span style={{
            fontFamily:'var(--mono)', fontSize:11, color:'var(--accent)',
            letterSpacing:'0.14em',
          }}>● live</span>
        </div>

        <div className="pg-grid">
          <div className="pg-side">
            <div>
              <h4>Modules</h4>
              {TABS.map(t => (
                <button
                  key={t.id}
                  className={`tab magnetic-trigger ${t.id === active ? 'active' : ''}`}
                  onClick={() => setActive(t.id)}
                >
                  <span className="tab-i">{t.i}</span>
                  <span>{t.l}</span>
                </button>
              ))}
            </div>
          </div>
          <div className="pg-body">
            <Tool />
          </div>
        </div>
      </div>
    </section>
  );
}

window.Playground = Playground;
