// ── Lambda Code Editor (CodeMirror wrapper) ────────────────────────────

function LambdaEditor({ value, onChange, placeholder }) {
  const containerRef = useRef(null);
  const editorRef = useRef(null);
  const callbackRef = useRef(onChange);
  callbackRef.current = onChange;

  useEffect(() => {
    if (!containerRef.current || editorRef.current) return;
    const cm = CodeMirror(containerRef.current, {
      value: value || '',
      mode: 'javascript',
      lineNumbers: true,
      matchBrackets: true,
      autoCloseBrackets: true,
      indentUnit: 2,
      tabSize: 2,
      indentWithTabs: false,
      lineWrapping: true,
      placeholder: placeholder || '',
      extraKeys: { 'Tab': (cm) => cm.replaceSelection('  ') },
    });
    cm.on('change', () => callbackRef.current(cm.getValue()));
    editorRef.current = cm;
    setTimeout(() => cm.refresh(), 50);
  }, []);

  useEffect(() => {
    if (editorRef.current && value !== editorRef.current.getValue()) {
      editorRef.current.setValue(value || '');
    }
  }, [value]);

  return (
    <div className="cm-wrapper" ref={containerRef} />
  );
}

// ── Lambda Help (collapsible reference) ─────────────────────────────────

function LambdaHelp() {
  const [open, setOpen] = useState(false);
  const exampleRef = useRef(null);
  const exampleCmRef = useRef(null);

  useEffect(() => {
    if (!open || !exampleRef.current || exampleCmRef.current) return;
    const cm = CodeMirror(exampleRef.current, {
      value: `(url, ctx) => {
  // ctx.ip — client IP address (string)
  // ctx.headers — filtered request headers (object)
  //
  // Available headers:
  //   ctx.headers['user-agent']
  //   ctx.headers['accept-language']
  //   ctx.headers['referer']
  //   ctx.headers['origin']
  //   ctx.headers['accept']
  //   ctx.headers['accept-encoding']
  //   ctx.headers['cache-control']
  //   ctx.headers['dnt']
  //   ctx.headers['x-forwarded-for']
  //   ctx.headers['x-real-ip']
  //   ctx.headers['x-forwarded-proto']
  //   ctx.headers['sec-ch-ua']
  //   ctx.headers['sec-ch-ua-mobile']
  //   ctx.headers['sec-ch-ua-platform']
  //   ctx.headers['sec-fetch-dest']
  //   ctx.headers['sec-fetch-mode']
  //   ctx.headers['sec-fetch-site']
  //   ctx.headers['if-none-match']
  //   ctx.headers['if-modified-since']
  //   ctx.headers['pragma']
  //
  // Sensitive headers (cookie, authorization,
  // x-invite-code) are stripped for security.

  // ── Example: geo-aware UTM tracking ──
  const lang = (ctx.headers['accept-language'] || '')
.split(',')[0] || 'en';
  const mobile = ctx.headers['sec-ch-ua-mobile'] === '?1';
  const device = mobile ? 'mobile' : 'desktop';

  const sep = url.includes('?') ? '&' : '?';
  return url + sep + [
'utm_source=vibey',
'utm_medium=' + device,
'lang=' + lang,
'ts=' + Date.now(),
  ].join('&');
}`,
      mode: 'javascript',
      lineNumbers: true,
      matchBrackets: true,
      readOnly: true,
      lineWrapping: true,
    });
    exampleCmRef.current = cm;
    setTimeout(() => cm.refresh(), 50);
  }, [open]);

  return (
    <div style={{marginTop:4}}>
      <button className="btn-ghost" onClick={() => setOpen(!open)}
              style={{fontSize:11,padding:'4px 10px',border:'none',color:'var(--accent)'}}>
        {open ? '▾ Hide' : '▸ Show'} Lambda Reference
      </button>
      {open && (
        <div style={{marginTop:8,background:'var(--bg)',border:'1px solid var(--border)',borderRadius:10,padding:16}}>
          <div style={{fontSize:12,color:'var(--text-dim)',marginBottom:12,lineHeight:1.6}}>
            Your lambda receives two arguments and must return a valid URL string.
            It runs in an isolated V8 sandbox with <strong style={{color:'var(--text)'}}>50ms</strong> timeout
            and <strong style={{color:'var(--text)'}}>16MB</strong> memory. The returned URL is
            re-validated against the security blacklist.
          </div>

          <div style={{fontSize:11,fontWeight:600,textTransform:'uppercase',letterSpacing:'0.06em',color:'var(--text-dim)',marginBottom:8}}>
            Full Example
          </div>
          <div className="cm-wrapper" ref={exampleRef} style={{marginBottom:12}} />

          <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:8,fontSize:12}}>
            <div style={{background:'var(--surface)',borderRadius:8,padding:'10px 12px'}}>
              <div style={{fontWeight:600,color:'var(--text)',marginBottom:4}}>Argument 1: url</div>
              <div style={{color:'var(--text-dim)'}}>The original destination URL as a string.</div>
            </div>
            <div style={{background:'var(--surface)',borderRadius:8,padding:'10px 12px'}}>
              <div style={{fontWeight:600,color:'var(--text)',marginBottom:4}}>Argument 2: ctx</div>
              <div style={{color:'var(--text-dim)'}}>Request context with <code style={{fontSize:11,color:'var(--accent)'}}>ctx.ip</code> and <code style={{fontSize:11,color:'var(--accent)'}}>ctx.headers</code>.</div>
            </div>
          </div>

          <div style={{marginTop:12,fontSize:11,color:'var(--text-dim)',lineHeight:1.6,background:'var(--surface)',borderRadius:8,padding:'10px 12px'}}>
            <strong style={{color:'var(--yellow)'}}>Rules:</strong> Must return a valid URL string. If execution
            exceeds 50ms, throws, or returns a blacklisted URL, the redirect fails with 403. During
            create/update the lambda is validated with test values (<code style={{fontSize:10,color:'var(--accent)'}}>ip: "127.0.0.1"</code>).
          </div>
        </div>
      )}
    </div>
  );
}
