// sections.jsx — stats, services accordion, portfolio rail, process, ticker, footer

const Stats = () => {
  const ref = React.useRef(null);
  useReveal(ref, { once: true });
  return (
    <section ref={ref} className="reveal" data-screen-label="02 Stats" style={{padding:"80px 0 48px"}}>
      <div className="wrap">
        <div style={{display:"grid",gridTemplateColumns:"repeat(4,1fr)",gap:0,borderTop:"1px solid var(--hair)",borderBottom:"1px solid var(--hair)"}}>
          {[
            {n:"25",   k:"Projects completed", v:"total · since 2021",   accent:"plus"},
            {n:"5",    k:"Developers",         v:"on the team",          accent:"plus"},
            {n:"2021", k:"Founded",            v:"Tbilisi · Remote",     accent:"dot"},
            {n:"24/7", k:"On call",            v:"Slack-first delivery", accent:"slash"},
          ].map(({n,k,v,accent},i)=>(
            <div key={i} style={{padding:"34px 24px",borderRight:i<3?"1px solid var(--hair)":"none",display:"flex",flexDirection:"column",gap:10}}>
              <div className="num-xl">{
                accent==="plus"  ? <>{n}<span className="accent">+</span></> :
                accent==="dot"   ? <>{n}<span className="accent">.</span></> :
                accent==="slash" ? <>{n.split("/")[0]}<span className="accent">/{n.split("/")[1]}</span></> :
                n
              }</div>
              <div className="mono" style={{fontSize:11,letterSpacing:".12em",color:"var(--mute)"}}>— {k.toUpperCase()}</div>
              <div style={{fontSize:13,color:"var(--ink-2)"}}>{v}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

const Ticker = () => (
  <section className="ticker" data-screen-label="03 Ticker">
    <div className="marquee">
      {Array.from({length:2}).map((_,i)=>(
        <React.Fragment key={i}>
          <span>WEB&nbsp;DEVELOPMENT</span>
          <span className="star">✦</span>
          <span><em>UI design</em></span>
          <span className="star">✦</span>
          <span>SEO&nbsp;&amp;&nbsp;PERFORMANCE</span>
          <span className="star">✦</span>
          <span><em>AI&nbsp;automations</em></span>
          <span className="star">✦</span>
          <span>CUSTOM&nbsp;AI&nbsp;SYSTEMS</span>
          <span className="star">✦</span>
          <span><em>shipped fast</em></span>
          <span className="star">✦</span>
        </React.Fragment>
      ))}
    </div>
  </section>
);

const Services = () => {
  const ref = React.useRef(null);
  useReveal(ref, { once: true });
  const items = [
    { n:"01", t:"Web development", tags:["NEXT.JS","SVELTEKIT","ASTRO"], copy:"From the marketing site to the dashboard behind the login. We write strict TypeScript, prefer boring infrastructure, and ship to production weekly so feedback loops stay short.", details:[
      ["Marketing & product sites","One-pagers · multi-page"],
      ["Web apps","Dashboards · portals · CMS"],
      ["E-commerce","Shopify · custom checkout"],
      ["Migrations","From WordPress · Webflow · Wix"],
      ["Engagement","Sprint · retainer · embed"],
    ]},
    { n:"02", t:"Web design / UI", tags:["FIGMA","HI-FI","SYSTEMS"], copy:"We treat the design like a product, not a deliverable: a working component library, motion notes, and a Figma file your team can actually keep alive after we leave.", details:[
      ["Brand-aligned web design","Hi-fi · interactive prototypes"],
      ["Design systems","Tokens · components · docs"],
      ["Audits & redesigns","With clear, measured opinions"],
      ["Motion","Subtle, performant, branded"],
      ["Handoff","Engineer-ready, not engineer-bait"],
    ]},
    { n:"03", t:"SEO & performance", tags:["CWV","SCHEMA","EAT"], copy:"Page speed and search visibility, treated as engineering problems. We measure, ship, measure again. No black hats, no &quot;content velocity,&quot; no nonsense.", details:[
      ["Core Web Vitals","Sub-1.5s LCP, sub-100ms INP"],
      ["Technical SEO","Schema · sitemaps · indexation"],
      ["Content architecture","Topical maps · pillar pages"],
      ["Programmatic pages","With editorial guardrails"],
      ["Analytics","Server-side · privacy-first"],
    ]},
    { n:"04", t:"AI automations & systems", tags:["RAG","AGENTS","EVALS"], copy:"Real systems with evals, not demos. We design the workflow first, choose models second, write guardrails third, and only then put it in front of customers.", details:[
      ["Internal copilots","Slack · email · CRM"],
      ["Customer-facing agents","With logs and rollback"],
      ["RAG over your docs","Notion · Drive · Linear"],
      ["Workflow automation","Zapier · n8n · custom"],
      ["Evaluation","We don't ship without scores"],
    ]},
  ];
  return (
    <section ref={ref} id="services" className="reveal" data-screen-label="04 Services" style={{padding:"40px 0 80px"}}>
      <div className="wrap">
        <div className="sec-head">
          <div>
            <div className="sec-num">[ §02 — PRACTICE ]</div>
            <div className="sec-title">Four things,<br/>done <span className="serif" style={{color:"var(--accent)"}}>uncommonly</span> well.</div>
          </div>
          <div className="mono" style={{fontSize:11,letterSpacing:".15em",color:"var(--mute)",maxWidth:280,textAlign:"right",lineHeight:1.7}}>
            ☞ Engagements typically run 3–8 weeks. We take on roughly one new project every six weeks.
          </div>
        </div>
        <div style={{marginTop:20}}>
          {items.map((it,idx)=>(
            <details className="acc" key={it.n} open={idx===0}>
              <summary>
                <div className="acc-num">[ {it.n} ]</div>
                <div className="acc-title">{it.t}</div>
                <div className="acc-tags">{it.tags.map(x=><span key={x} className="pill" style={{height:22,fontSize:10}}>{x}</span>)}</div>
                <div className="plus">
                  <svg width="14" height="14" viewBox="0 0 14 14"><line x1="0" y1="7" x2="14" y2="7" stroke="currentColor" strokeWidth="1.4"/><line x1="7" y1="0" x2="7" y2="14" stroke="currentColor" strokeWidth="1.4"/></svg>
                </div>
              </summary>
              <div className="acc-body">
                <div>
                  <p>{it.copy}</p>
                  <div style={{marginTop:14,display:"flex",gap:8,flexWrap:"wrap"}}>
                    {it.tags.map(x=><span key={x} className="pill" style={{background:"var(--ink)",color:"var(--paper)",borderColor:"var(--ink)"}}>{x}</span>)}
                  </div>
                </div>
                <ul>
                  {it.details.map(([a,b],i)=><li key={i}><b>{a}</b><span>{b}</span></li>)}
                </ul>
              </div>
            </details>
          ))}
        </div>
      </div>
    </section>
  );
};

const Portfolio = () => {
  const railRef = React.useRef(null);
  const headRef = React.useRef(null);
  const [idx, setIdx] = React.useState(1);
  useReveal(headRef, { once: true });

  // drag-to-scroll
  React.useEffect(() => {
    const el = railRef.current; if(!el) return;
    let down = false, sx = 0, sl = 0, moved = false;
    const onDown = (e) => { down=true;moved=false; sx = e.pageX; sl = el.scrollLeft; el.classList.add("dragging"); };
    const onMove = (e) => { if(!down) return; const dx = e.pageX - sx; if(Math.abs(dx)>4) moved=true; el.scrollLeft = sl - dx; };
    const onUp = () => { down=false; el.classList.remove("dragging"); };
    el.addEventListener("pointerdown", onDown);
    window.addEventListener("pointermove", onMove);
    window.addEventListener("pointerup", onUp);
    const onScroll = () => {
      const cards = el.querySelectorAll(".case");
      const center = el.scrollLeft + el.clientWidth/2;
      let best = 0, bd = Infinity;
      cards.forEach((c,i)=>{ const cc = c.offsetLeft + c.offsetWidth/2; const d = Math.abs(cc-center); if(d<bd){bd=d;best=i;} });
      setIdx(best+1);
    };
    el.addEventListener("scroll", onScroll, { passive:true });
    return () => {
      el.removeEventListener("pointerdown", onDown);
      window.removeEventListener("pointermove", onMove);
      window.removeEventListener("pointerup", onUp);
      el.removeEventListener("scroll", onScroll);
    };
  }, []);

  const scrollBy = (dir) => {
    const el = railRef.current; if(!el) return;
    const card = el.querySelector(".case");
    const w = card ? card.offsetWidth + 24 : 600;
    el.scrollBy({ left: dir*w, behavior:"smooth" });
  };

  return (
    <section id="work" data-screen-label="05 Portfolio" style={{padding:"40px 0 40px"}}>
      <div className="wrap">
        <div ref={headRef} className="reveal sec-head" style={{borderTop:"1px solid var(--hair)",paddingTop:24}}>
          <div>
            <div className="sec-num">[ §03 — SELECTED WORK · 2024 — 26 ]</div>
            <div className="sec-title">Recent shipments — for <span className="serif" style={{color:"var(--accent)"}}>founders</span>,<br/>brands, and the teams behind them.</div>
          </div>
          <div style={{display:"flex",alignItems:"center",gap:14}}>
            <span className="mono" style={{fontSize:11,letterSpacing:".15em",color:"var(--mute)"}}>{String(idx).padStart(2,"0")} / {String(window.MOCKS.length).padStart(2,"0")}</span>
            <button onClick={()=>scrollBy(-1)} aria-label="prev" style={{width:42,height:42,borderRadius:99,border:"1px solid var(--ink)",background:"transparent"}}>←</button>
            <button onClick={()=>scrollBy(1)} aria-label="next" style={{width:42,height:42,borderRadius:99,border:"1px solid var(--ink)",background:"var(--ink)",color:"var(--paper)"}}>→</button>
          </div>
        </div>
      </div>

      <div ref={railRef} className="rail">
        {window.MOCKS.map((m,i)=>{
          const C = m.c;
          return (
            <a key={i} href="#" className="case" onClick={(e)=>e.preventDefault()}>
              <div className="frame">
                <div className="browser">
                  <div className="bar">
                    <span className="d"/><span className="d"/><span className="d"/>
                    <div className="url">
                      <span style={{opacity:.5}}>https://</span>{m.url}
                    </div>
                    <span className="mono" style={{fontSize:9,opacity:.45}}>{m.year}</span>
                  </div>
                  <C/>
                </div>
                <div className="open-badge">
                  <svg width="14" height="14" viewBox="0 0 14 14"><path d="M3 11 L11 3 M5 3 L11 3 L11 9" stroke="currentColor" strokeWidth="1.4" fill="none"/></svg>
                </div>
              </div>
              <div className="meta">
                <div>
                  <div className="row" style={{marginBottom:6}}><span className="mono">[ {String(i+1).padStart(2,"0")} ]</span><span>{m.tag.toUpperCase()}</span><span>· {m.role.toUpperCase()}</span></div>
                  <h3>{m.title}</h3>
                </div>
                <div className="mono" style={{fontSize:11,opacity:.55,whiteSpace:"nowrap"}}>↗ {m.url}</div>
              </div>
            </a>
          );
        })}
        <div style={{flex:"0 0 32px"}}/>
      </div>

      <div className="wrap" style={{display:"flex",justifyContent:"space-between",alignItems:"center",borderTop:"1px solid var(--hair)",paddingTop:18,marginTop:8,fontFamily:"'JetBrains Mono',monospace",fontSize:11,letterSpacing:".1em",color:"var(--mute)"}}>
        <span>↤ DRAG · OR USE ARROWS</span>
        <span>SHIPPED, NOT MOCKED. EACH CASE HAS A LIVE URL.</span>
        <span>⌁ {window.MOCKS.length} CASES</span>
      </div>
    </section>
  );
};

const Process = () => {
  const ref = React.useRef(null);
  useReveal(ref, { once: true });
  const steps = [
    ["W—01","Listen","30-minute intro. We map the problem and the people, not the deliverables."],
    ["W—02","Plan","A scope, a timeline, a price. Fixed. We've never sent a change-order without a reason."],
    ["W—03","Make","Async-first delivery: a Loom every Friday, a Figma you can comment in, a staging URL that loads."],
    ["W—04","Ship","Launch, then a 14-day &quot;quiet period&quot; where we sit on it and iron out anything we missed."],
  ];
  return (
    <section ref={ref} id="process" className="reveal" data-screen-label="06 Process" style={{padding:"40px 0 60px"}}>
      <div className="wrap">
        <div className="sec-head">
          <div>
            <div className="sec-num">[ §04 — METHOD ]</div>
            <div className="sec-title">Four weeks. Four steps.<br/>One <span className="serif" style={{color:"var(--accent)"}}>quiet</span> handoff.</div>
          </div>
          <div className="mono" style={{fontSize:11,letterSpacing:".15em",color:"var(--mute)",textAlign:"right",lineHeight:1.7,maxWidth:280}}>
            ☞ Variable for AI projects (≈8 wk) and migrations (≈3 wk). Sprint-based retainers available after launch.
          </div>
        </div>
        <div className="steps" style={{marginTop:14}}>
          {steps.map(([k,t,c])=>(
            <div key={k} className="step">
              <span className="k">{k}</span>
              <h4>{t}</h4>
              <p>{c}</p>
              <span className="mono" style={{fontSize:10,opacity:.5,letterSpacing:".15em"}}>↘ continue</span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

const Contact = () => {
  const ref = React.useRef(null);
  useReveal(ref, { once: true });
  return (
    <section ref={ref} id="contact" className="reveal" data-screen-label="07 Contact" style={{padding:"60px 0 40px"}}>
      <div className="wrap">
        <div style={{display:"grid",gridTemplateColumns:"1.4fr 1fr",gap:48,alignItems:"end",borderTop:"1px solid var(--hair)",paddingTop:32}}>
          <div>
            <div className="sec-num">[ §05 — ENGAGE ]</div>
            <div style={{fontSize:"clamp(48px,7vw,108px)",fontWeight:800,letterSpacing:"-.045em",lineHeight:.92,marginTop:8}}>
              Let's build the<br/>
              <span className="serif" style={{color:"var(--accent)",fontWeight:400}}>thing</span> that earns<br/>
              its load time.
            </div>
            <div style={{display:"flex",gap:12,marginTop:28,flexWrap:"wrap"}}>
              <a href="tel:+995557470982" className="btn"><span className="dot"/> +995 557 470 982</a>
              <a href="#work" className="btn ghost">See selected work →</a>
            </div>
          </div>
          <div style={{display:"flex",flexDirection:"column",gap:14,fontFamily:"'JetBrains Mono',monospace",fontSize:11,letterSpacing:".05em",color:"var(--ink-2)"}}>
            <div style={{display:"flex",justifyContent:"space-between",borderBottom:"1px solid var(--hair)",padding:"10px 0"}}><span>STUDIO HOURS</span><span>MON—FRI · 09:00 — 19:00 GET</span></div>
            <div style={{display:"flex",justifyContent:"space-between",borderBottom:"1px solid var(--hair)",padding:"10px 0"}}><span>RESPONSE</span><span>≤ 4 HOURS, BUSINESS DAY</span></div>
            <div style={{display:"flex",justifyContent:"space-between",borderBottom:"1px solid var(--hair)",padding:"10px 0"}}><span>FIT CALL</span><span>30 MIN · NO PITCH</span></div>
            <div style={{display:"flex",justifyContent:"space-between",borderBottom:"1px solid var(--hair)",padding:"10px 0"}}><span>NDA</span><span>WE'LL SIGN YOURS, OR USE OURS</span></div>
            <div style={{display:"flex",justifyContent:"space-between",padding:"10px 0"}}><span>NEXT OPENING</span><span style={{color:"var(--accent)"}}>● Q3 · 2026</span></div>
          </div>
        </div>
      </div>
    </section>
  );
};

const Footer = () => (
  <footer data-screen-label="08 Footer">
    <div className="wrap">
      <div className="foot-row" style={{padding:"24px 0",borderTop:"1px solid var(--hair)",borderBottom:"1px solid var(--hair)"}}>
        <div className="mono" style={{fontSize:11,letterSpacing:".1em",color:"var(--mute)"}}>
          © 2026 — CODE-PAL · INDEPENDENT WEB STUDIO
        </div>
        <div style={{display:"flex",gap:18,fontFamily:"'JetBrains Mono',monospace",fontSize:11,letterSpacing:".1em",color:"var(--ink-2)"}}>
          <a href="#">↗ DRIBBBLE</a><a href="#">↗ READ.CV</a><a href="#">↗ GITHUB</a><a href="#">↗ LINKEDIN</a>
        </div>
        <div className="mono" style={{fontSize:11,letterSpacing:".1em",color:"var(--mute)"}}>
          ⌁ BUILT IN TBILISI · COFFEE · LATE NIGHTS
        </div>
      </div>
      <div className="foot-bigword" style={{padding:"40px 0 8px"}}>
        CODE—<span style={{color:"var(--accent)"}}>PAL</span><span className="serif spin" style={{display:"inline-block",fontWeight:400,fontStyle:"italic",fontSize:".25em",verticalAlign:"super",color:"var(--accent)",marginLeft:".1em"}}>✦</span>
      </div>
    </div>
  </footer>
);

const Nav = () => (
  <nav className="nav">
    <div className="wrap row">
      <div className="logo">
        <span className="mark">/</span>
        <span>code-pal<span style={{color:"var(--accent)"}}>.</span></span>
      </div>
      <div className="nav-links">
        <a href="#services">Practice</a>
        <a href="#work">Work</a>
        <a href="#process">Method</a>
        <a href="#contact">Engage</a>
      </div>
      <a href="#contact" className="btn"><span className="dot"/> Start a project</a>
    </div>
  </nav>
);

window.Stats = Stats; window.Ticker = Ticker; window.Services = Services;
window.Portfolio = Portfolio; window.Process = Process; window.Contact = Contact;
window.Footer = Footer; window.Nav = Nav;
