const { useState, useEffect, useMemo, useRef } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accent": "#FF6B35",
  "accent2": "#FFB088",
  "bookingFlow": "stepped"
}/*EDITMODE-END*/;

const ACCENT_PRESETS = [
  { name: "Amber", a: "#FF6B35", b: "#FFB088" },
  { name: "Lime",  a: "#B8FF4A", b: "#E2FFA8" },
  { name: "Sky",   a: "#5AB8FF", b: "#A8DCFF" },
  { name: "Violet",a: "#A78BFA", b: "#D4C5FF" },
  { name: "Rose",  a: "#FF6B9D", b: "#FFB0CC" }
];

const CALENDLY_WIDGET_SRC = "https://assets.calendly.com/assets/external/widget.js";
const CALENDLY_EVENT_URL = "https://calendly.com/mousaa/30min";
const POST_BOOKING_URL = "/post-booking.html";

function applyAccent(a, b){
  const root = document.documentElement.style;
  root.setProperty("--accent", a);
  root.setProperty("--accent-2", b);
  // glow color from a
  const glow = a + "59"; // ~35% alpha hex
  root.setProperty("--accent-glow", glow);
}

// ---------- Icons ----------
const Ico = {
  arrow: ()=> <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round"><line x1="5" y1="12" x2="19" y2="12"/><polyline points="12 5 19 12 12 19"/></svg>,
  check: ()=> <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>,
  clock: ()=> <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>,
  cam:  ()=> <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polygon points="23 7 16 12 23 17 23 7"/><rect x="1" y="5" width="15" height="14" rx="2" ry="2"/></svg>,
  globe: ()=> <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>,
  chevL:()=> <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="15 18 9 12 15 6"/></svg>,
  chevR:()=> <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="9 18 15 12 9 6"/></svg>,
  fox:  ()=> <svg viewBox="0 0 24 24" fill="#1a0d05"><path d="M4 4l4 5h8l4-5-2 11c-.5 3-3 5-6 5s-5.5-2-6-5L4 4zm6 9.5a1 1 0 110-2 1 1 0 010 2zm4 0a1 1 0 110-2 1 1 0 010 2z"/></svg>,
};

// ---------- NAV ----------
function Nav(){
  const [menuOpen, setMenuOpen] = useState(false);
  const closeMenu = () => setMenuOpen(false);

  return (
    <>
      <nav className="top">
        <div className="container row">
          <a href="/" className="logo">
            <span className="logo-mark"><Ico.fox/></span>
            Fox AI
          </a>
          <ul className="desktop">
            <li><a href="#how">How it works</a></li>
            <li><a href="#features">Features</a></li>
            <li><a href="#pricing">Pricing</a></li>
            <li><a href="#faq">FAQ</a></li>
          </ul>
          <div className="right">
            <a href="https://app.usefox.ai/login" style={{color:"var(--muted)",fontSize:14}}>Sign in</a>
            <a href="#book" className="btn btn-primary">Book a strategy call <Ico.arrow/></a>
          </div>
          <button className={"hamburger" + (menuOpen ? " open" : "")} onClick={() => setMenuOpen(!menuOpen)} aria-label="Toggle menu">
            <span/><span/><span/>
          </button>
        </div>
      </nav>

      <div className={"mobile-nav" + (menuOpen ? " show" : "")}>
        <a href="#how" onClick={closeMenu}>How it works</a>
        <a href="#features" onClick={closeMenu}>Features</a>
        <a href="#pricing" onClick={closeMenu}>Pricing</a>
        <a href="#faq" onClick={closeMenu}>FAQ</a>
        <a href="https://app.usefox.ai/login" onClick={closeMenu}>Sign in</a>
        <a href="#book" className="btn btn-primary" onClick={closeMenu}>Book a strategy call <Ico.arrow/></a>
      </div>
    </>
  );
}

// ---------- HERO ----------
function Hero(){
  return (
    <section className="hero">
      <div className="container">
        <span className="eyebrow"><span className="dot"/> Now onboarding 50 founders / month</span>
        <h1>Grow organic traffic <span className="serif">on autopilot.</span></h1>
        <p className="sub">Fox AI is the autonomous SEO engine for founders. We research keywords, write expert articles, build backlinks, and publish daily — so you wake up to traffic instead of a blank Notion doc.</p>
        <div className="ctas">
          <a href="#book" className="btn btn-primary">Book a strategy call <Ico.arrow/></a>
          <a href="#how" className="btn btn-ghost">See how it works</a>
        </div>
        <div className="meta">
          <span className="avatars">
            <span className="a" style={{background:"linear-gradient(135deg,#7a4f2c,#3d2715)"}}>JR</span>
            <span className="a" style={{background:"linear-gradient(135deg,#5a3a8a,#2c1d4a)"}}>AT</span>
            <span className="a" style={{background:"linear-gradient(135deg,#2d6b4f,#143426)"}}>MK</span>
            <span className="a" style={{background:"linear-gradient(135deg,#8a4a4a,#4a1f1f)"}}>SL</span>
          </span>
          <span><span className="stars">★★★★★</span> &nbsp; 4.9 from 280+ founders</span>
          <span>•</span>
          <span><span className="check">✓</span> 1.2M articles published</span>
          <span>•</span>
          <span><span className="check">✓</span> 38M sessions driven</span>
        </div>

        <HeroVisual/>
      </div>
    </section>
  );
}

function HeroVisual(){
  return (
    <div className="hero-visual">
      <div className="dash">
        <aside className="dash-side">
          <div className="label">Content engine</div>
          <div className="item active">
            <svg className="ic" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
            Calendar
          </div>
          <div className="item">
            <svg className="ic" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 113 3L7 19l-4 1 1-4L16.5 3.5z"/></svg>
            Drafts <span style={{marginLeft:"auto",fontSize:10,color:"var(--accent)"}}>8</span>
          </div>
          <div className="item">
            <svg className="ic" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>
            Briefs <span style={{marginLeft:"auto",fontSize:10,color:"var(--accent)"}}>12</span>
          </div>
          <div className="item">
            Review <span style={{marginLeft:"auto",fontSize:10,color:"var(--accent)"}}>3</span>
          </div>
          <div className="item">
            <svg className="ic" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polyline points="20 6 9 17 4 12"/></svg>
            Published
          </div>
        </aside>
        <div className="dash-main">
          <div className="dash-head">
            <div>
              <h3>Content calendar</h3>
              <div style={{color:"var(--muted)",fontSize:13,marginTop:2}}>Next 14 days · acmeshop.io</div>
            </div>
            <div style={{display:"flex",gap:8,alignItems:"center"}}>
              <span className="pill">6 posts scheduled</span>
            </div>
          </div>
          <div className="dash-stats">
            <div className="stat"><div className="k">This week</div><div className="v">5</div><div className="d">posts queued</div></div>
            <div className="stat"><div className="k">In review</div><div className="v">3</div><div className="d">awaiting approval</div></div>
            <div className="stat"><div className="k">Briefs ready</div><div className="v">12</div><div className="d">from research</div></div>
            <div className="stat"><div className="k">Published</div><div className="v">18</div><div className="d">this month</div></div>
          </div>
          <ContentCalendar/>
        </div>
      </div>
    </div>
  );
}

function ContentCalendar(){
  const posts = [
    { day: "Mon", date: "18", title: "AI SEO checklist", status: "Ready", tone: "good" },
    { day: "Tue", date: "19", title: "SaaS keyword map", status: "Drafting", tone: "accent" },
    { day: "Wed", date: "20", title: "Product-led content", status: "Review", tone: "warn" },
    { day: "Thu", date: "21", title: "Backlink outreach", status: "Queued", tone: "accent" },
    { day: "Fri", date: "22", title: "Founder SEO audit", status: "Briefed", tone: "good" },
  ];
  const toneColor = {
    good: "var(--good)",
    accent: "var(--accent)",
    warn: "var(--accent-2)",
  };
  return (
    <div className="chart" style={{display:"flex",flexDirection:"column",gap:14,minHeight:210}}>
      <div className="chart-head">
        <span>Publishing calendar</span>
        <span style={{color:"var(--accent)"}}>● Daily content plan</span>
      </div>
      <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(116px,1fr))",gap:10}}>
        {posts.map((post)=>(
          <div key={post.date} style={{minHeight:128,border:"1px solid var(--line)",borderRadius:10,padding:12,background:"rgba(255,255,255,.018)",display:"flex",flexDirection:"column",gap:10}}>
            <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",fontSize:11,color:"var(--muted)"}}>
              <span>{post.day}</span>
              <span className="mono">{post.date}</span>
            </div>
            <div style={{fontSize:13,fontWeight:600,lineHeight:1.25,color:"var(--text)"}}>{post.title}</div>
            <div style={{marginTop:"auto",fontSize:10,fontWeight:700,letterSpacing:".04em",textTransform:"uppercase",color:toneColor[post.tone],border:"1px solid rgba(255,255,255,.1)",borderRadius:999,padding:"4px 7px",width:"fit-content"}}>
              {post.status}
            </div>
          </div>
        ))}
      </div>
      <div style={{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(220px,1fr))",gap:12}}>
        <div style={{border:"1px solid var(--line)",borderRadius:10,padding:14,background:"rgba(255,107,53,.04)"}}>
          <div style={{fontSize:11,color:"var(--muted-2)",textTransform:"uppercase",letterSpacing:".08em",fontWeight:700}}>Next article brief</div>
          <div style={{marginTop:8,fontSize:14,fontWeight:700}}>How to build a SaaS SEO moat before competitors wake up</div>
          <div style={{marginTop:8,color:"var(--muted)",fontSize:12,lineHeight:1.45}}>Target keyword, outline, internal links, and image prompt prepared for approval.</div>
        </div>
        <div style={{border:"1px solid var(--line)",borderRadius:10,padding:14,background:"rgba(255,255,255,.015)"}}>
          <div style={{fontSize:11,color:"var(--muted-2)",textTransform:"uppercase",letterSpacing:".08em",fontWeight:700}}>Workflow</div>
          <div style={{marginTop:8,display:"flex",flexDirection:"column",gap:7,color:"var(--muted)",fontSize:12}}>
            <span><strong style={{color:"var(--text)"}}>Research</strong> complete</span>
            <span><strong style={{color:"var(--text)"}}>Draft</strong> queued</span>
            <span><strong style={{color:"var(--text)"}}>Publish</strong> scheduled</span>
          </div>
        </div>
      </div>
    </div>
  );
}

// ---------- LOGOS ----------
function Logos(){
  const names = ["Strategy","Calendar","Drafts","Publishing","Backlinks","Reporting"];
  return (
    <div className="logos">
      <div className="container">
        <div className="label">Built around the SEO work founders need shipped</div>
        <div className="logo-row">
          {names.map((n,i)=>(
            <div key={i} className="l">
              <span style={{width:14,height:14,borderRadius:4,background:"var(--muted)",opacity:.4}}/>
              {n}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// ---------- PROBLEM ----------
function Problem(){
  return (
    <section id="problem">
      <div className="container">
        <div className="sec-head">
          <span className="eyebrow">The honest truth</span>
          <h2>SEO is the highest-ROI channel <span className="serif">nobody actually does.</span></h2>
          <p>Every founder knows organic traffic compounds. Almost nobody does it consistently — because doing it right is slow, expensive, and unbearably manual.</p>
        </div>
        <div className="problem-grid">
          <div className="problem-card bad">
            <div className="label">Without Fox AI</div>
            <h3>You're stuck in the SEO doom loop.</h3>
            <ul>
              <li><span className="ico">✕</span><span><strong style={{color:"var(--text)"}}>$5K/mo agencies</strong> deliver 4 mediocre articles a month and won't tell you why.</span></li>
              <li><span className="ico">✕</span><span><strong style={{color:"var(--text)"}}>Tools like Ahrefs and Semrush</strong> need a full-time human to actually use them.</span></li>
              <li><span className="ico">✕</span><span><strong style={{color:"var(--text)"}}>You publish for 2 weeks</strong>, get pulled into product, and don't ship again for 6 months.</span></li>
              <li><span className="ico">✕</span><span><strong style={{color:"var(--text)"}}>Paid ads</strong> stop the moment you stop paying. You own nothing.</span></li>
            </ul>
            <FlatChart trend="bad"/>
          </div>
          <div className="problem-card good">
            <div className="label">With Fox AI</div>
            <h3>Your SEO ships every single day.</h3>
            <ul>
              <li><span className="ico">✓</span><span><strong style={{color:"var(--text)"}}>30 expert articles a month</strong> researched, written, and published — automatically.</span></li>
              <li><span className="ico">✓</span><span><strong style={{color:"var(--text)"}}>Continuous keyword discovery</strong> tuned to what's actually moving in your niche.</span></li>
              <li><span className="ico">✓</span><span><strong style={{color:"var(--text)"}}>Real backlinks</strong> from a vetted network — not link farms.</span></li>
              <li><span className="ico">✓</span><span><strong style={{color:"var(--text)"}}>One flat fee.</strong> No per-article billing, no agency markups, no surprises.</span></li>
            </ul>
            <FlatChart trend="good"/>
          </div>
        </div>
      </div>
    </section>
  );
}

function FlatChart({trend}){
  const w=320, h=80, pad=4;
  const points = useMemo(()=>{
    const pts=[];
    for (let i=0;i<32;i++){
      if (trend==="bad"){
        pts.push(20 + Math.sin(i*0.4)*6 + (Math.random()-0.5)*4 - i*0.1);
      } else {
        pts.push(8 + Math.pow(i/31,2)*52 + (Math.random()-0.5)*3);
      }
    }
    return pts;
  },[trend]);
  const max = Math.max(...points,40);
  const path = points.map((p,i)=>{
    const x = pad + (i/(points.length-1))*(w-pad*2);
    const y = h-pad - (Math.max(0,p)/max)*(h-pad*2);
    return `${i===0?'M':'L'}${x.toFixed(1)} ${y.toFixed(1)}`;
  }).join(" ");
  const color = trend==="bad" ? "var(--bad)" : "var(--accent)";
  return (
    <div className="mini-graph">
      <svg viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none">
        <path d={path} fill="none" stroke={color} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" opacity=".9"/>
      </svg>
      <div style={{position:"absolute",top:14,left:14,fontSize:11,color:"var(--muted-2)",textTransform:"uppercase",letterSpacing:".08em",fontWeight:600}}>
        {trend==="bad" ? "Traffic — flat" : "Traffic — compounding"}
      </div>
    </div>
  );
}

// ---------- HOW IT WORKS ----------
function HowItWorks(){
  return (
    <section id="how">
      <div className="container">
        <div className="sec-head">
          <span className="eyebrow">How it works</span>
          <h2>Onboard in 5 minutes. <span className="serif">Compound for years.</span></h2>
          <p>Drop in your URL. Fox AI studies your business, finds the keywords your buyers are actually typing, and starts shipping daily.</p>
        </div>
        <div className="steps">
          <div className="step">
            <span className="num">01</span>
            <h3>Connect your site</h3>
            <p>Paste your URL. We scan your product, audience, competitors, and existing rankings — no questionnaire, no kickoff calls.</p>
            <div className="visual">
              <div className="ln" style={{color:"var(--accent-2)"}}>$ fox connect acmeshop.io</div>
              <div className="ln"><span className="ck">✓</span> Site analyzed (47 pages)</div>
              <div className="ln"><span className="ck">✓</span> Found 12 competitors</div>
              <div className="ln"><span className="ck">✓</span> Ingested 3 GSC properties</div>
              <div className="ln" style={{color:"var(--text)"}}>→ 1,847 keywords identified</div>
            </div>
          </div>
          <div className="step">
            <span className="num">02</span>
            <h3>We pick the winners</h3>
            <p>Continuous keyword discovery surfaces the searches with real intent and beatable competition — and queues them for production.</p>
            <div className="visual">
              <div style={{marginBottom:6}}>Top picks this week:</div>
              <span className="kw">best shopify alternatives</span>
              <span className="kw">how to reduce CAC</span>
              <span className="kw">notion vs linear</span>
              <span className="kw">chargebee pricing</span>
              <span className="kw">stripe atlas review</span>
              <span className="kw">indie hacker SEO</span>
            </div>
          </div>
          <div className="step">
            <span className="num">03</span>
            <h3>Daily content + links</h3>
            <p>One expert article ships every day, fully optimized, with internal links and on-brand images — plus monthly backlinks from our vetted network.</p>
            <div className="visual">
              <div className="ln"><span className="ck">▶</span> Mon — "Notion vs Linear: 2026 deep dive" <span style={{color:"var(--good)"}}>published</span></div>
              <div className="ln"><span className="ck">▶</span> Tue — "Shopify alternatives ranked" <span style={{color:"var(--good)"}}>published</span></div>
              <div className="ln"><span className="ck">▶</span> Wed — "How to reduce CAC for SaaS" <span style={{color:"var(--good)"}}>published</span></div>
              <div className="ln"><span className="ck">▶</span> Thu — "Stripe Atlas review" <span style={{color:"var(--accent)"}}>publishing…</span></div>
              <div className="ln" style={{color:"var(--muted-2)"}}>+ 2 backlinks placed this week</div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

// ---------- FEATURES ----------
function Features(){
  return (
    <section id="features">
      <div className="container">
        <div className="sec-head">
          <span className="eyebrow">What's inside</span>
          <h2>An entire SEO team, <span className="serif">running while you sleep.</span></h2>
        </div>
        <div className="features">
          <div className="feature wide tall">
            <div className="ico-circle">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="11" cy="11" r="7"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
            </div>
            <h3>Continuous keyword discovery</h3>
            <p>Most tools give you a list once. Fox AI re-runs discovery weekly — catching trending searches, new competitor angles, and seasonal demand before your competitors do.</p>
            <div className="visual" style={{padding:"16px",alignItems:"flex-start",flexDirection:"column",gap:8}}>
              <div className="kw-table">
                <div className="row head"><span>KEYWORD</span><span>VOL</span><span>DIFF</span><span>INTENT</span></div>
                {[
                  ["best ai seo tool", "8.1K", "32", "🟢 buy"],
                  ["seo automation", "12K", "44", "🟢 buy"],
                  ["how to write blog posts", "27K", "28", "🟡 info"],
                  ["content marketing 2026", "4.4K", "21", "🟢 buy"],
                ].map((r,i)=>(
                  <div key={i} className="row">
                    <span className="kw">{r[0]}</span><span>{r[1]}</span><span>{r[2]}</span><span>{r[3]}</span>
                  </div>
                ))}
              </div>
            </div>
          </div>

          <div className="feature wide">
            <div className="ico-circle">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 113 3L7 19l-4 1 1-4L16.5 3.5z"/></svg>
            </div>
            <h3>Expert articles, not AI fluff</h3>
            <p>Every piece is fact-checked, cited, and written in your brand voice — 1,500–2,500 words with infographics, internal links, and a real point of view.</p>
          </div>

          <div className="feature wide">
            <div className="ico-circle">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M10 13a5 5 0 007.54.54l3-3a5 5 0 00-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 00-7.54-.54l-3 3a5 5 0 007.07 7.07l1.71-1.71"/></svg>
            </div>
            <h3>Vetted backlink network</h3>
            <p>Real, indexed sites — checked by hand, monitored continuously. If a link drops, we replace it. Zero PBNs, zero spam.</p>
          </div>

          <div className="feature">
            <div className="ico-circle">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M21 16V8a2 2 0 00-1-1.73l-7-4a2 2 0 00-2 0l-7 4A2 2 0 003 8v8a2 2 0 001 1.73l7 4a2 2 0 002 0l7-4A2 2 0 0021 16z"/></svg>
            </div>
            <h3>Auto-publish</h3>
            <p>WordPress, Webflow, Shopify, Framer, Ghost, Notion. One click.</p>
          </div>

          <div className="feature">
            <div className="ico-circle">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 014 10 15.3 15.3 0 01-4 10 15.3 15.3 0 01-4-10 15.3 15.3 0 014-10z"/></svg>
            </div>
            <h3>50+ languages</h3>
            <p>Localized for whatever market you're attacking next.</p>
          </div>

          <div className="feature">
            <div className="ico-circle">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M22 11.08V12a10 10 0 11-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
            </div>
            <h3>Approve or autopilot</h3>
            <p>Review every article before it ships, or let Fox run hands-off.</p>
          </div>

          <div className="feature">
            <div className="ico-circle">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"/></svg>
            </div>
            <h3>Live dashboard</h3>
            <p>Track every article, link, and ranking in real time — not in a quarterly PDF.</p>
          </div>
        </div>
      </div>
    </section>
  );
}

// ---------- PRICING ----------
function Pricing(){
  return (
    <section id="pricing">
      <div className="container">
        <div className="sec-head">
          <span className="eyebrow">Pricing</span>
          <h2>One plan. <span className="serif">All of it.</span></h2>
          <p>No seat fees. No per-article billing. No "let me get on a call with our solutions consultant."</p>
        </div>
        <div className="price-card">
          <span className="badge">Best ROI on the market</span>
          <div className="label">Founder plan</div>
          <div className="amount">
            <span className="n">$99</span>
            <span className="p">/ month, all-in</span>
          </div>
          <div style={{color:"var(--muted)",fontSize:14}}>3-day trial · Cancel anytime · No card games</div>
          <ul>
            <li><span className="ck"><Ico.check/></span><span>30 expert articles published every month</span></li>
            <li><span className="ck"><Ico.check/></span><span>Continuous keyword research & competitor tracking</span></li>
            <li><span className="ck"><Ico.check/></span><span>Backlink network — real sites, monitored</span></li>
            <li><span className="ck"><Ico.check/></span><span>Auto-publish to WordPress, Webflow, Shopify, Framer, Ghost, Notion</span></li>
            <li><span className="ck"><Ico.check/></span><span>50+ languages, internal linking, on-brand imagery</span></li>
            <li><span className="ck"><Ico.check/></span><span>Live dashboard — see every article and link as it ships</span></li>
          </ul>
          <a href="#book" className="btn btn-primary">Book a strategy call <Ico.arrow/></a>
        </div>
      </div>
    </section>
  );
}

// ---------- FAQ ----------
function FAQ(){
  const items = [
    ["How is this different from ChatGPT?","ChatGPT gives you a draft. Fox AI runs the entire pipeline — keyword research tuned to your business, expert articles with citations, internal linking, image generation, daily auto-publishing, backlink building, and ranking tracking. You spend zero hours; it just runs."],
    ["Will Google penalize me for AI content?","No. Google's stance is 'rewards quality, regardless of how it's produced.' Our articles are fact-checked, cited, and consistently outrank human-written agency content. We've shipped 1.2M articles across 1,200+ sites — the data is conclusive."],
    ["What's the catch with $99?","Honestly, no catch. We built a single autonomous engine and scaled it to thousands of customers. The marginal cost per article is tiny. We'd rather have 10,000 happy founders at $99 than 100 enterprise contracts."],
    ["What if I don't see results?","SEO compounds — most customers see meaningful traffic lift in 60–90 days. If you're not happy in your first month, we refund you. The 3-day trial lets you see article quality before you commit."],
    ["Do you handle backlinks?","Yes — through a vetted network of real, indexed sites. Every site is checked by hand, monitored continuously, and replaced if a link drops. Zero PBNs, zero link farms."],
    ["What CMS do you support?","WordPress, Webflow, Shopify, Framer, Ghost, Notion, Wix, and any site via webhook or REST API. Setup is a single OAuth click."],
  ];
  return (
    <section id="faq">
      <div className="container">
        <div className="sec-head">
          <span className="eyebrow">FAQ</span>
          <h2>You probably have <span className="serif">a few questions.</span></h2>
        </div>
        <div className="faq">
          {items.map(([q,a],i)=>(
            <details key={i} className="qa" open={i===0}>
              <summary>{q}<span className="plus">+</span></summary>
              <p>{a}</p>
            </details>
          ))}
        </div>
      </div>
    </section>
  );
}

// ---------- BOOKING ----------
function CalendlyWidget(){
  useEffect(()=>{
    function handleCalendlyMessage(event){
      if (event.origin !== "https://calendly.com") return;
      if (event.data?.event !== "calendly.event_scheduled") return;

      window.location.href = POST_BOOKING_URL;
    }

    function initializeCalendly(){
      if (window.Calendly?.initInlineWidgets) {
        window.Calendly.initInlineWidgets();
      }
    }

    window.addEventListener("message", handleCalendlyMessage);

    const existingScript = document.querySelector(`script[src="${CALENDLY_WIDGET_SRC}"]`);
    if (existingScript) {
      existingScript.addEventListener("load", initializeCalendly);
      initializeCalendly();
      return () => {
        window.removeEventListener("message", handleCalendlyMessage);
        existingScript.removeEventListener("load", initializeCalendly);
      };
    }

    const script = document.createElement("script");
    script.type = "text/javascript";
    script.src = CALENDLY_WIDGET_SRC;
    script.async = true;
    script.addEventListener("load", initializeCalendly);
    document.body.appendChild(script);

    return () => {
      window.removeEventListener("message", handleCalendlyMessage);
      script.removeEventListener("load", initializeCalendly);
    };
  },[]);

  return (
    <div className="calendly-inline-widget" data-url={CALENDLY_EVENT_URL} style={{minWidth:320,height:760}}/>
  );
}

function todayMidnight(){ const d=new Date(); d.setHours(0,0,0,0); return d; }
function fmtDate(d){ return d.toLocaleDateString("en-US",{weekday:"long",month:"long",day:"numeric"}); }
function fmtMonthYear(d){ return d.toLocaleDateString("en-US",{month:"long",year:"numeric"}); }

function generateSlots(date){
  // pseudo-deterministic slot list per date
  if (!date) return [];
  const day = date.getDay();
  if (day===0 || day===6) return []; // closed weekends
  const seed = date.getDate();
  const slots = [];
  const starts = ["09:00","09:30","10:00","10:30","11:00","13:00","13:30","14:00","14:30","15:00","15:30","16:00"];
  starts.forEach((s,i)=>{
    if ((seed+i) % 3 !== 0) slots.push(s); // skip ~1/3
  });
  return slots;
}

function fmt12(t){
  const [h,m] = t.split(":").map(Number);
  const ampm = h>=12 ? "pm":"am";
  const hh = ((h+11)%12)+1;
  return `${hh}:${m.toString().padStart(2,"0")} ${ampm}`;
}

function BookingWidget({flow}){
  const [monthCursor, setMonthCursor] = useState(()=>{ const d=todayMidnight(); d.setDate(1); return d; });
  const [selectedDay, setSelectedDay] = useState(null);
  const [selectedSlot, setSelectedSlot] = useState(null);
  const [committedSlot, setCommittedSlot] = useState(null);
  const [step, setStep] = useState("pick"); // pick | details | confirmed
  const [tz, setTz] = useState("12h");
  const [form, setForm] = useState({name:"",email:"",company:"",website:"",mrr:"<$10K",notes:""});
  const [touched, setTouched] = useState(false);

  const today = todayMidnight();
  const monthDays = useMemo(()=>{
    const first = new Date(monthCursor);
    const lastDay = new Date(first.getFullYear(), first.getMonth()+1, 0).getDate();
    const startWeekday = first.getDay();
    const cells = [];
    for (let i=0;i<startWeekday;i++) cells.push({empty:true});
    for (let d=1; d<=lastDay; d++){
      const date = new Date(first.getFullYear(), first.getMonth(), d);
      const isPast = date < today;
      const isWeekend = date.getDay()===0 || date.getDay()===6;
      const slots = generateSlots(date);
      const tooFar = (date - today) > 1000*60*60*24*45;
      const disabled = isPast || isWeekend || slots.length===0 || tooFar;
      cells.push({date, disabled, hasSlots: slots.length>0 && !disabled, isToday: date.getTime()===today.getTime()});
    }
    return cells;
  },[monthCursor]);

  const slots = useMemo(()=> generateSlots(selectedDay), [selectedDay]);

  const canPrev = monthCursor > new Date(today.getFullYear(), today.getMonth(), 1);
  function shiftMonth(delta){
    const d = new Date(monthCursor); d.setMonth(d.getMonth()+delta); setMonthCursor(d);
    setSelectedDay(null); setSelectedSlot(null);
  }

  // single-page flow renders details inline below time picking
  const isStepped = flow === "stepped";

  function commitSlot(){
    setCommittedSlot(selectedSlot);
    if (isStepped){ setStep("details"); }
  }

  function submit(e){
    e?.preventDefault();
    setTouched(true);
    if (!form.name || !form.email || !form.email.includes("@")) return;
    setStep("confirmed");
  }

  const meetingDate = selectedDay && committedSlot
    ? `${fmtDate(selectedDay)} · ${fmt12(committedSlot)} – ${fmt12(addMinutes(committedSlot,30))}`
    : null;

  function addMinutes(t,mins){
    const [h,m]=t.split(":").map(Number);
    const total = h*60+m+mins;
    const hh = Math.floor(total/60).toString().padStart(2,"0");
    const mm = (total%60).toString().padStart(2,"0");
    return `${hh}:${mm}`;
  }

  if (step==="confirmed"){
    return (
      <div className="book-shell">
        <div className="book-confirmed active">
          <div className="check-big">
            <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
          </div>
          <h3>You're booked, {form.name.split(" ")[0] || "friend"}.</h3>
          <p>A calendar invite is on its way to <strong style={{color:"var(--text)"}}>{form.email}</strong>. Reply to it with anything you want me to look at before we hop on.</p>
          <div className="ical">
            <div className="calmark">
              <span className="m">{selectedDay.toLocaleDateString("en-US",{month:"short"})}</span>
              <span className="d">{selectedDay.getDate()}</span>
            </div>
            <div>
              <div style={{fontWeight:600,fontSize:15}}>Strategy call with Fox AI</div>
              <div style={{color:"var(--muted)",fontSize:13,marginTop:2}}>{meetingDate}</div>
              <div style={{color:"var(--muted)",fontSize:13,marginTop:2}}>30 min · Google Meet</div>
            </div>
          </div>
          <a className="btn btn-primary" href={POST_BOOKING_URL}>View preparation steps <Ico.arrow/></a>
          <button className="btn btn-ghost" onClick={()=>{setStep("pick");setSelectedSlot(null);setCommittedSlot(null);setForm({name:"",email:"",company:"",website:"",mrr:"<$10K",notes:""});setTouched(false);}}>
            Book another time
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="book-shell">
      {(!isStepped || step==="pick") && (
        <div className="book-grid">
          <BookingInfo/>
          <div className="book-cal">
            <div className="book-cal-head">
              <h4>{fmtMonthYear(monthCursor)}</h4>
              <div className="nav">
                <button onClick={()=>shiftMonth(-1)} disabled={!canPrev} aria-label="Previous month"><Ico.chevL/></button>
                <button onClick={()=>shiftMonth(1)} aria-label="Next month"><Ico.chevR/></button>
              </div>
            </div>
            <div className="cal-grid">
              {["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].map(d=> <div key={d} className="dn">{d.slice(0,2)}</div>)}
              {monthDays.map((c,i)=>{
                if (c.empty) return <div key={i} className="cal-day empty"/>;
                const cls = ["cal-day"];
                if (c.disabled) cls.push("disabled");
                else if (c.hasSlots) cls.push("has-slots");
                if (c.isToday) cls.push("today");
                if (selectedDay && c.date && selectedDay.getTime()===c.date.getTime()) cls.push("selected");
                return (
                  <div key={i} className={cls.join(" ")} onClick={()=>{
                    if (c.disabled) return;
                    setSelectedDay(c.date); setSelectedSlot(null);
                  }}>{c.date.getDate()}</div>
                );
              })}
            </div>
            <div style={{marginTop:18,fontSize:12,color:"var(--muted-2)",display:"flex",gap:14,alignItems:"center"}}>
              <span style={{display:"inline-flex",alignItems:"center",gap:6}}><span style={{width:6,height:6,borderRadius:"50%",background:"var(--accent)"}}/> Available</span>
              <span style={{display:"inline-flex",alignItems:"center",gap:6}}><span style={{width:6,height:6,borderRadius:"50%",background:"var(--muted-2)",opacity:.5}}/> No slots</span>
            </div>
          </div>
          <div className="book-times">
            <h4>{selectedDay ? fmtDate(selectedDay) : "Pick a date"}</h4>
            <div className="sub">{selectedDay ? `${slots.length} slots available` : "Times will appear here"}</div>
            <div className="tz-toggle">
              <button className={tz==="12h"?"active":""} onClick={()=>setTz("12h")}>12-hour</button>
              <button className={tz==="24h"?"active":""} onClick={()=>setTz("24h")}>24-hour</button>
            </div>
            {selectedDay ? (
              <div className="slots">
                {slots.length===0 ? (
                  <div className="slots-empty">Nothing free on this day.</div>
                ) : slots.map(s=>(
                  <div key={s} className={"slot" + (selectedSlot===s ? " selected":"")}>
                    <button className="t" onClick={()=>setSelectedSlot(s)}>
                      {tz==="12h" ? fmt12(s) : s}
                    </button>
                    {selectedSlot===s && (
                      <button className="confirm" onClick={commitSlot}>
                        {isStepped ? "Next" : "Confirm"}
                      </button>
                    )}
                  </div>
                ))}
              </div>
            ) : (
              <div className="slots-empty">← Select a date with a dot</div>
            )}
          </div>
        </div>
      )}

      {/* Single-page flow: details inline below */}
      {!isStepped && committedSlot && (
        <div className="book-details active" style={{borderTop:"1px solid var(--line)"}}>
          <DetailsForm form={form} setForm={setForm} touched={touched} submit={submit} meetingDate={meetingDate}
            onChange={()=>{setCommittedSlot(null);}} />
        </div>
      )}

      {/* Stepped flow: full-width details panel */}
      {isStepped && step==="details" && (
        <div className="book-details active">
          <DetailsForm form={form} setForm={setForm} touched={touched} submit={submit} meetingDate={meetingDate}
            onChange={()=>{setStep("pick"); setCommittedSlot(null);}} />
        </div>
      )}
    </div>
  );
}

function BookingInfo(){
  return (
    <aside className="book-info">
      <div style={{display:"flex",gap:14,alignItems:"center"}}>
        <div className="who-av">JR</div>
        <div>
          <h3>Strategy call with Fox AI</h3>
          <div className="role">30 min · Google Meet</div>
        </div>
      </div>
      <p className="desc">A focused 30 minutes. Bring your URL and your traffic goals — leave with a content plan, a backlink target, and a candid take on whether Fox AI is right for you.</p>
      <div className="meta">
        <div className="row"><Ico.clock/><span>30 minutes</span></div>
        <div className="row"><Ico.cam/><span>Google Meet (link emailed)</span></div>
        <div className="row"><Ico.globe/><span>Times in your local time zone</span></div>
      </div>
      <div className="agenda">
        <div className="label">What we'll cover</div>
        <ul>
          <li>Your current SEO baseline (we'll audit before the call)</li>
          <li>3 keyword opportunities specific to your niche</li>
          <li>Realistic 90-day projection</li>
          <li>Whether Fox is — or isn't — a fit</li>
        </ul>
      </div>
    </aside>
  );
}

function DetailsForm({form,setForm,touched,submit,meetingDate,onChange}){
  function set(k,v){ setForm(f=>({...f,[k]:v})); }
  const emailErr = touched && (!form.email || !form.email.includes("@"));
  const nameErr = touched && !form.name;
  return (
    <form onSubmit={submit} style={{display:"flex",flexDirection:"column",gap:18}}>
      <div className="summary">
        <span className="ic"><Ico.clock/></span>
        <span><strong>{meetingDate}</strong> &nbsp;·&nbsp; 30 min · Google Meet</span>
        <span className="change" onClick={onChange}>Change time</span>
      </div>
      <h3>One last step.</h3>
      <div className="form-row">
        <div className="field">
          <label>Your name *</label>
          <input value={form.name} onChange={e=>set("name",e.target.value)} placeholder="Jamie Founder" style={nameErr?{borderColor:"var(--bad)"}:{}}/>
        </div>
        <div className="field">
          <label>Email *</label>
          <input type="email" value={form.email} onChange={e=>set("email",e.target.value)} placeholder="jamie@yourstartup.com" style={emailErr?{borderColor:"var(--bad)"}:{}}/>
        </div>
      </div>
      <div className="form-row">
        <div className="field">
          <label>Company</label>
          <input value={form.company} onChange={e=>set("company",e.target.value)} placeholder="Your company"/>
        </div>
        <div className="field">
          <label>Website</label>
          <input value={form.website} onChange={e=>set("website",e.target.value)} placeholder="acmeshop.io"/>
        </div>
      </div>
      <div className="form-row">
        <div className="field">
          <label>Current MRR</label>
          <select value={form.mrr} onChange={e=>set("mrr",e.target.value)}>
            <option>Pre-revenue</option>
            <option>&lt;$10K</option>
            <option>$10K–$50K</option>
            <option>$50K–$250K</option>
            <option>$250K+</option>
          </select>
        </div>
        <div className="field">
          <label>Where did you hear about us?</label>
          <input placeholder="Twitter, friend, podcast…"/>
        </div>
      </div>
      <div className="field">
        <label>What's your single biggest SEO frustration right now?</label>
        <textarea value={form.notes} onChange={e=>set("notes",e.target.value)} placeholder="The more specific, the more useful the call will be."/>
      </div>
      <div className="submit-row">
        <button type="button" className="btn btn-ghost" onClick={onChange}>Back</button>
        <button type="submit" className="btn btn-primary">Confirm booking <Ico.arrow/></button>
      </div>
    </form>
  );
}

// ---------- BOOKING SECTION ----------
function BookingSection({flow}){
  return (
    <section id="book" className="book">
      <div className="container">
        <div className="sec-head">
          <span className="eyebrow"><span className="dot"/> Limited slots this week</span>
          <h2>Book a 30-minute <span className="serif">strategy call.</span></h2>
          <p>No pitch. We'll audit your site live, show you the top 3 keywords we'd attack first, and give you a realistic 90-day projection. If Fox AI isn't a fit, we'll tell you straight.</p>
        </div>
        <div className="book-shell calendly-shell">
          <CalendlyWidget/>
        </div>
      </div>
    </section>
  );
}

// ---------- FOOTER ----------
function Footer(){
  return (
    <footer>
      <div className="container">
        <div className="row">
          <div style={{maxWidth:300}}>
            <a href="/" className="logo"><span className="logo-mark"><Ico.fox/></span> Fox AI</a>
            <p style={{color:"var(--muted)",fontSize:14,marginTop:14,lineHeight:1.6}}>The fastest way to grow organic traffic — without effort, without agencies, without managing anyone.</p>
          </div>
          <div className="col">
            <h5>Product</h5>
            <a href="#how">How it works</a><a href="#features">Features</a><a href="#pricing">Pricing</a>
          </div>
          <div className="col">
            <h5>Resources</h5>
            <a href="#faq">FAQ</a><a href="#book">Book a call</a>
          </div>
          <div className="col">
            <h5>Company</h5>
            <a href="https://app.usefox.ai/login">Sign in</a><a href="mailto:hello@foxai.so">Contact</a>
          </div>
        </div>
        <div className="bottom">
          <span>© 2026 Fox AI · Made for founders who'd rather be shipping product.</span>
          <span>hello@foxai.so</span>
        </div>
      </div>
    </footer>
  );
}

// ---------- TWEAKS ----------
function Tweaks({tweaks, setTweak}){
  return (
    <TweaksPanel title="Tweaks">
      <TweakSection title="Brand">
        <div style={{display:"flex",gap:8,flexWrap:"wrap"}}>
          {ACCENT_PRESETS.map(p=>(
            <button key={p.name} onClick={()=>setTweak({accent:p.a, accent2:p.b})}
              style={{
                padding:"8px 12px",borderRadius:8,border:"1px solid",
                borderColor: tweaks.accent===p.a ? p.a : "rgba(255,255,255,.14)",
                background: tweaks.accent===p.a ? p.a+"22" : "transparent",
                color:"#f5f1ea",fontSize:12,fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",gap:6
              }}>
              <span style={{width:10,height:10,borderRadius:"50%",background:p.a}}/>
              {p.name}
            </button>
          ))}
        </div>
        <TweakColor label="Custom accent" value={tweaks.accent} onChange={v=>setTweak({accent:v})}/>
      </TweakSection>
      <TweakSection title="Booking flow">
        <TweakRadio
          value={tweaks.bookingFlow}
          onChange={v=>setTweak({bookingFlow:v})}
          options={[
            {value:"stepped", label:"Stepped"},
            {value:"single", label:"Single page"},
          ]}
        />
        <p style={{margin:0,fontSize:12,color:"#9a948a",lineHeight:1.5}}>
          <strong style={{color:"#f5f1ea"}}>Stepped:</strong> calendar → details on a separate screen.<br/>
          <strong style={{color:"#f5f1ea"}}>Single page:</strong> details appear inline below the time picker.
        </p>
      </TweakSection>
    </TweaksPanel>
  );
}

// ---------- APP ----------
function App(){
  const [tweaks, setTweak] = useTweaks(TWEAK_DEFAULTS);

  useEffect(()=>{
    applyAccent(tweaks.accent, tweaks.accent2);
  },[tweaks.accent, tweaks.accent2]);

  return (
    <>
      <Nav/>
      <Hero/>
      <Logos/>
      <Problem/>
      <HowItWorks/>
      <Features/>
      <Pricing/>
      <FAQ/>
      <BookingSection flow={tweaks.bookingFlow}/>
      <Footer/>
      <Tweaks tweaks={tweaks} setTweak={setTweak}/>
    </>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App/>);
