// app.jsx — TradeTank landing app (React)
const { useState, useEffect, useRef } = React;

// ── Defaults persisted by host ──────────────────────────────────────
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "bgVariant": "candles",
  "intensity": 1,
  "returning": false,
  "returningName": "Olivia",
  "returningEmail": "olivia@hooked.io",
  "accent": "#F97316",
  "headline": "cast",
  "fontTheme": "poppins"
} /*EDITMODE-END*/;

const ACCENT_OPTIONS = ['#F97316', '#10b981', '#F59E0B', '#06b6d4'];

const FONT_THEMES = {
  poppins: {
    display: "'Poppins', system-ui, sans-serif",
    body: "'Poppins', system-ui, sans-serif",
    mono: "'JetBrains Mono', monospace",
    weight: '800',
    tracking: '-0.035em'
  }
};

const HEADLINES = {
  cast: {
    line1: <>Enter the tank.</>,
    line2: <>Land bigger <span style={{ whiteSpace: "nowrap" }}><span className="accent" style={{ fontFamily: "Karla" }}>fish</span><img src="traddy.png" alt="" className="traddy-inline" /></span></>
  },
  fishing: {
    line1: <>Stop fishing for profits</>,
    line2: <>without a <span className="accent">net.</span></>
  },
  net: {
    line1: <>The net for</>,
    line2: <><span className="accent">serious</span> traders.</>
  }
};

// ─────────────────────────────────────────────────────────────────────
// AUTH CARD
// ─────────────────────────────────────────────────────────────────────
function AuthCard({ returning, returningName, returningEmail, onSwitchUser }) {
  const [tab, setTab] = useState('signup');
  const [email, setEmail] = useState('');
  const [pw, setPw] = useState('');
  const [name, setName] = useState('');
  const [loading, setLoading] = useState(false);
  const [shake, setShake] = useState(false);

  useEffect(() => {
    if (returning) setEmail(returningEmail);
  }, [returning, returningEmail]);

  const submit = (e) => {
    e.preventDefault();
    if (!email) {
      setShake(true);
      setTimeout(() => setShake(false), 500);
      return;
    }
    setLoading(true);
    setTimeout(() => setLoading(false), 1400);
  };

  // ── Returning-user variant ──
  if (returning) {
    const initial = (returningName || 'T').charAt(0).toUpperCase();
    return (
      <div className="auth" style={shake ? { animation: 'shake .4s' } : null}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 18 }}>
          <div className="auth-returning-avatar">{initial}</div>
          <div>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 600, letterSpacing: '-0.01em' }}>
              Welcome back, {returningName}.
            </div>
            <div style={{ fontSize: 12.5, color: 'var(--text-faint)', fontFamily: 'var(--font-mono)' }}>
              {returningEmail}
            </div>
          </div>
        </div>

        <form onSubmit={submit}>
          <div className="field">
            <label>Password</label>
            <input
              type="password"
              placeholder="Password"
              value={pw}
              onChange={(e) => setPw(e.target.value)}
              autoFocus />
            
          </div>
          <div className="field-row">
            <label><input type="checkbox" defaultChecked />Remember me</label>
            <a href="#" onClick={(e) => e.preventDefault()}>Forgot password?</a>
          </div>
          <button type="submit" className="auth-submit" disabled={loading}>
            {loading ? <Spinner /> : <>Reel me in <Arrow /></>}
          </button>
        </form>

        <div className="switch-user">
          Not {returningName}? <button onClick={onSwitchUser}>Sign in differently</button>
        </div>
      </div>);

  }

  // ── Waitlist CTA variant ──
  return (
    <div className="auth">
      <a href="#join" id="home-join-cta" className="auth-submit" style={{textDecoration:'none', display:'flex', alignItems:'center', justifyContent:'center', gap:8}}>
        Join the waitlist <Arrow />
      </a>
    </div>);

}

// ─────────────────────────────────────────────────────────────────────
// HERO CONTENT
// ─────────────────────────────────────────────────────────────────────
function HeroContent({ headline }) {
  const h = HEADLINES[headline] || HEADLINES.cast;
  return (
    <>
      <h1>
        <span className="line" style={{ fontFamily: "Poppins", fontWeight: "700", lineHeight: "0.95" }}>{h.line1}</span>
        <span className="line" style={{ fontFamily: "Poppins", fontWeight: "700", lineHeight: "0.95" }}>{h.line2}</span>
      </h1>


      <div className="trust-row">
        <div className="trust-chip">
          <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6">
            <circle cx="8" cy="8" r="6" />
            <path d="M8 4v4l3 2" />
          </svg>
          <span>Setup in <b>less than a minute</b></span>
        </div>
        <div className="trust-divider"></div>
        <div className="trust-chip">
          <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6">
            <path d="M2 11l3-3 3 2 6-6" />
            <path d="M9 4h5v5" />
          </svg>
          <span>Track <b>every trade</b></span>
        </div>
        <div className="trust-divider"></div>
        <div className="trust-chip">
          <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6">
            <path d="M8 1l6 3v4c0 4-2.7 6.5-6 7-3.3-.5-6-3-6-7V4l6-3z" />
            <path d="M5 8l2 2 4-4" />
          </svg>
          <span>Secure payments via <b>Stripe</b></span>
        </div>
      </div>
    </>);

}

// ─────────────────────────────────────────────────────────────────────
// TWEAKS PANEL
// ─────────────────────────────────────────────────────────────────────
function TweaksRoot() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  // Apply to BG scene + CSS vars
  useEffect(() => {
    if (window.BgScene) window.BgScene.setVariant(t.bgVariant);
  }, [t.bgVariant]);
  useEffect(() => {
    if (window.BgScene) window.BgScene.setIntensity(t.intensity);
  }, [t.intensity]);
  useEffect(() => {
    document.documentElement.style.setProperty('--accent', t.accent);
    document.documentElement.style.setProperty('--accent-dim', darken(t.accent, 0.18));
    if (window.BgScene) window.BgScene.setAccent(t.accent);
  }, [t.accent]);
  useEffect(() => {
    const f = FONT_THEMES[t.fontTheme] || FONT_THEMES.poppins;
    const r = document.documentElement.style;
    r.setProperty('--font-display', f.display);
    r.setProperty('--font-body', f.body);
    r.setProperty('--font-mono', f.mono);
    r.setProperty('--headline-weight', f.weight);
    r.setProperty('--headline-tracking', f.tracking);
  }, [t.fontTheme]);

  return (
    <>
      <div id="hero-mount-target"></div>
      <HeroMount headline={t.headline} />
      <AuthMount
        returning={t.returning}
        returningName={t.returningName}
        returningEmail={t.returningEmail}
        onSwitchUser={() => setTweak('returning', false)} />
      

      <TweaksPanel>
        <TweakSection label="Background" />
        <TweakRadio
          label="Style"
          value={t.bgVariant}
          options={['candles', 'sparklines', 'orderflow']}
          onChange={(v) => setTweak('bgVariant', v)} />
        
        <TweakSlider
          label="Intensity"
          value={t.intensity}
          min={0.3} max={1.8} step={0.1}
          onChange={(v) => setTweak('intensity', v)} />
        

        <TweakSection label="Brand" />
        <TweakColor
          label="Accent"
          value={t.accent}
          options={ACCENT_OPTIONS}
          onChange={(v) => setTweak('accent', v)} />
        
        <TweakSelect
          label="Headline"
          value={t.headline}
          options={[
          { label: 'Cast a line. Land bigger fish.', value: 'cast' },
          { label: 'Stop fishing for profits.', value: 'fishing' },
          { label: 'The net for serious traders.', value: 'net' }]
          }
          onChange={(v) => setTweak('headline', v)} />
        

        <TweakSection label="Returning visitor" />
        <TweakToggle
          label="Show 'Welcome back'"
          value={t.returning}
          onChange={(v) => setTweak('returning', v)} />
        
        {t.returning &&
        <>
            <TweakText
            label="Name"
            value={t.returningName}
            onChange={(v) => setTweak('returningName', v)} />
          
            <TweakText
            label="Email"
            value={t.returningEmail}
            onChange={(v) => setTweak('returningEmail', v)} />
          
          </>
        }
      </TweaksPanel>
    </>);

}

// Mount hero content into static #hero (so the original h1 can still be direct-edited
// — actually because hero is mounted by React based on a tweak, we render it via portal-ish replace).
function HeroMount({ headline }) {
  useEffect(() => {
    const host = document.getElementById('hero');
    if (!host) return;
    // remove any previous react root
    if (host._reactRoot) host._reactRoot.unmount();
    const root = ReactDOM.createRoot(host);
    host._reactRoot = root;
    root.render(<HeroContent headline={headline} />);
    return () => {/* cleanup handled on next mount */};
  }, [headline]);
  return null;
}

function AuthMount({ returning, returningName, returningEmail, onSwitchUser }) {
  useEffect(() => {
    const host = document.getElementById('auth-root');
    if (!host) return;
    if (!host._reactRoot) host._reactRoot = ReactDOM.createRoot(host);
    host._reactRoot.render(
      <AuthCard
        returning={returning}
        returningName={returningName}
        returningEmail={returningEmail}
        onSwitchUser={onSwitchUser} />

    );
  }, [returning, returningName, returningEmail]);
  return null;
}

// ─────────────────────────────────────────────────────────────────────
// SMALL ATOMS
// ─────────────────────────────────────────────────────────────────────
function GoogleIcon() {
  return (
    <svg viewBox="0 0 18 18" xmlns="http://www.w3.org/2000/svg">
      <path d="M17.64 9.2c0-.64-.06-1.25-.16-1.84H9v3.48h4.84c-.21 1.13-.85 2.08-1.8 2.72v2.26h2.91c1.7-1.57 2.69-3.88 2.69-6.62z" fill="#4285F4" />
      <path d="M9 18c2.43 0 4.47-.81 5.95-2.18l-2.91-2.26c-.81.54-1.84.86-3.04.86-2.34 0-4.32-1.58-5.03-3.7H.96v2.33C2.44 15.98 5.48 18 9 18z" fill="#34A853" />
      <path d="M3.97 10.71A5.41 5.41 0 0 1 3.68 9c0-.6.1-1.18.29-1.71V4.96H.96A9 9 0 0 0 0 9c0 1.45.35 2.82.96 4.04l3.01-2.33z" fill="#FBBC05" />
      <path d="M9 3.58c1.32 0 2.5.45 3.44 1.34l2.58-2.58C13.46.89 11.42 0 9 0 5.48 0 2.44 2.02.96 4.96L3.97 7.3C4.68 5.16 6.66 3.58 9 3.58z" fill="#EA4335" />
    </svg>);

}

function AppleIcon() {
  return (
    <svg viewBox="0 0 18 18" xmlns="http://www.w3.org/2000/svg" fill="currentColor">
      <path d="M14.94 13.78c-.27.61-.59 1.18-.97 1.7-.51.71-.93 1.2-1.25 1.47-.5.45-1.04.68-1.61.69-.41 0-.91-.12-1.49-.36-.58-.24-1.11-.36-1.6-.36-.51 0-1.06.12-1.65.36-.59.24-1.07.37-1.43.39-.55.02-1.1-.22-1.65-.71-.35-.3-.79-.81-1.32-1.55-.56-.78-1.03-1.69-1.39-2.74C.39 11.55.18 10.46.18 9.42c0-1.2.26-2.24.78-3.1A4.57 4.57 0 0 1 2.59 4.7a4.4 4.4 0 0 1 2.21-.62c.44 0 1.02.14 1.74.4.72.27 1.18.41 1.38.41.15 0 .67-.16 1.55-.48.83-.3 1.53-.42 2.11-.37 1.55.12 2.72.74 3.49 1.85-1.39.84-2.07 2.02-2.06 3.53.02 1.17.44 2.15 1.27 2.92.38.36.8.64 1.27.83-.1.3-.21.59-.32.88zM11.65.36c0 .9-.33 1.73-.98 2.51-.79.92-1.74 1.45-2.78 1.37a3.07 3.07 0 0 1-.02-.34c0-.86.37-1.78 1.04-2.54.33-.39.76-.71 1.27-.97.51-.26 1-.4 1.46-.43.01.13.01.27.01.4z" />
    </svg>);

}

function Arrow() {
  return (
    <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <line x1="2" y1="8" x2="13" y2="8" />
      <polyline points="9 4 13 8 9 12" />
    </svg>);

}

function Spinner() {
  return (
    <svg viewBox="0 0 24 24" width="18" height="18">
      <circle cx="12" cy="12" r="9" fill="none" stroke="rgba(255,255,255,0.3)" strokeWidth="3" />
      <path d="M12 3a9 9 0 0 1 9 9" fill="none" stroke="#fff" strokeWidth="3" strokeLinecap="round">
        <animateTransform attributeName="transform" type="rotate" from="0 12 12" to="360 12 12" dur="0.8s" repeatCount="indefinite" />
      </path>
    </svg>);

}

// hex utils
function darken(hex, amt) {
  const h = hex.replace('#', '');
  let r = parseInt(h.substring(0, 2), 16);
  let g = parseInt(h.substring(2, 4), 16);
  let b = parseInt(h.substring(4, 6), 16);
  r = Math.max(0, Math.round(r * (1 - amt)));
  g = Math.max(0, Math.round(g * (1 - amt)));
  b = Math.max(0, Math.round(b * (1 - amt)));
  return '#' + [r, g, b].map((x) => x.toString(16).padStart(2, '0')).join('');
}

// ─── shake keyframe (injected once) ───
(function injectShake() {
  const s = document.createElement('style');
  s.textContent = `@keyframes shake {
    0%,100%{transform:translateX(0)}
    20%{transform:translateX(-6px)}
    40%{transform:translateX(6px)}
    60%{transform:translateX(-4px)}
    80%{transform:translateX(4px)}
  }`;
  document.head.appendChild(s);
})();

// ── MOUNT ──────────────────────────────────────────────────────────
const tweaksRoot = ReactDOM.createRoot(document.getElementById('tweaks-root'));
tweaksRoot.render(<TweaksRoot />);