const { useState: useS1, useEffect: useE1, useRef: useR1, useMemo: useM1 } = React;

// ---------- Hero ----------
const REVIEWS = [
  { src:'Google',   rating:5, author:'Danielle R.', text:'Fixed my leaky sink in under 20 minutes. Absolute wizard with a wrench.', biz:'Pete\'s Plumbing', t:'2s ago', loc:'Austin, TX' },
  { src:'Yelp',     rating:2, author:'Marcus K.',   text:'Coffee was cold, waiter was colder. Nice vibes though I guess.',        biz:'Blue Door Cafe', t:'11s ago', loc:'Brooklyn, NY' },
  { src:'Facebook', rating:5, author:'Amy L.',      text:'Third time here and still obsessed. The tiramisu? Life-changing.',       biz:'Luna Bistro',    t:'29s ago', loc:'Seattle, WA' },
  { src:'Tripadvisor', rating:4, author:'Jorge P.', text:'Bed was comfy, breakfast so-so, view worth the whole trip.',             biz:'Harbor Inn',     t:'41s ago', loc:'Portland, ME' },
  { src:'Trustpilot',  rating:1, author:'Aisha T.', text:'Package arrived soaking wet. Support was slow. Would not reorder.',       biz:'LoomWear',       t:'1m ago', loc:'Denver, CO' },
  { src:'Booking',     rating:5, author:'Ken W.',   text:'Hosts left fresh cookies. Cookies! At a hotel! 10/10.',                   biz:'The Rosewood',   t:'1m ago', loc:'Nashville, TN' },
  { src:'Google',   rating:4, author:'Priya S.',    text:'Haircut was exactly what I asked for. Parking was a nightmare.',          biz:'Blade & Bloom',  t:'2m ago', loc:'Chicago, IL' },
];

const SRC_COLORS = {
  Google:     'oklch(0.62 0.17 250)',
  Yelp:       'oklch(0.58 0.19 25)',
  Facebook:   'oklch(0.52 0.15 260)',
  Tripadvisor:'oklch(0.60 0.14 150)',
  Trustpilot: 'oklch(0.62 0.16 150)',
  Booking:    'oklch(0.50 0.18 255)',
};

const Stars = ({n, max=5}) => (
  <span style={{display:'inline-flex', gap:1, color:'var(--coral)'}}>
    {Array.from({length:max}).map((_,i)=>(
      <svg key={i} width="12" height="12" viewBox="0 0 12 12" fill={i<n?'currentColor':'var(--rule)'}>
        <path d="M6 1 L7.5 4.5 L11 5 L8.5 7.5 L9 11 L6 9.3 L3 11 L3.5 7.5 L1 5 L4.5 4.5 Z"/>
      </svg>
    ))}
  </span>
);

const ReviewCard = ({r, compact}) => (
  <div style={{
    background:'var(--paper)', border:'1px solid var(--rule)', borderRadius:12, padding:compact?12:14,
    display:'flex', flexDirection:'column', gap:8, minWidth: compact?260:300, maxWidth: compact?280:320,
    boxShadow:'0 1px 0 rgba(0,0,0,0.02)',
  }}>
    <div style={{display:'flex', alignItems:'center', justifyContent:'space-between'}}>
      <div style={{display:'flex', alignItems:'center', gap:7}}>
        <span style={{width:18, height:18, borderRadius:4, background:SRC_COLORS[r.src], color:'white', fontSize:10, fontWeight:700, display:'grid', placeItems:'center'}}>{r.src[0]}</span>
        <span style={{fontSize:12, color:'var(--ink-2)', fontWeight:500}}>{r.src}</span>
        <Stars n={r.rating}/>
      </div>
      <span className="mono" style={{fontSize:11, color:'var(--ink-3)'}}>{r.t}</span>
    </div>
    <div style={{fontSize:13.5, color:'var(--ink)', lineHeight:1.45, textWrap:'pretty'}}>"{r.text}"</div>
    <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', fontSize:11.5, color:'var(--ink-3)'}}>
      <span>{r.author} · {r.biz}</span>
      <span className="mono">{r.loc}</span>
    </div>
  </div>
);

const Hero = ({variant='ticker'}) => {
  const [count, setCount] = useS1(48213421);
  useE1(()=>{
    const id = setInterval(()=> setCount(c => c + Math.floor(Math.random()*6)+2), 500);
    return ()=>clearInterval(id);
  },[]);

  return (
    <section style={{position:'relative', paddingTop:80, paddingBottom:96, overflow:'hidden'}}>
      {/* Speech-bubble ambient grid */}
      <div aria-hidden style={{
        position:'absolute', inset:0, pointerEvents:'none', opacity:.35,
        backgroundImage:`radial-gradient(circle at 1px 1px, var(--rule-2) 1px, transparent 0)`,
        backgroundSize:'28px 28px', maskImage:'linear-gradient(180deg, transparent, black 20%, black 70%, transparent)',
      }}/>
      <div className="wrap" style={{position:'relative', display:'grid', gridTemplateColumns:'1.1fr 1fr', gap:64, alignItems:'start'}}>
        <div>
          <Pill tone="shout" style={{marginBottom:22}}>
            <Dot c="var(--shout)"/> Review infrastructure · since 2012
          </Pill>
          <h1 style={{
            fontSize:'clamp(48px, 6vw, 84px)', lineHeight:0.96, letterSpacing:'-0.035em', margin:'0 0 22px',
            fontWeight:600, textWrap:'balance',
          }}>
            The review<br/>
            management <span className="serif" style={{color:'var(--shout)', fontWeight:400}}>API</span>
            <br/>that does the <span style={{position:'relative', display:'inline-block'}}>
              heavy lifting.
              <svg width="100%" height="14" style={{position:'absolute', left:0, bottom:-6}} viewBox="0 0 320 14" preserveAspectRatio="none">
                <path d="M2 8 Q 80 2, 160 8 T 318 8" stroke="var(--shout)" strokeWidth="3" fill="none" strokeLinecap="round"/>
              </svg>
            </span>
          </h1>
          <p style={{fontSize:19, color:'var(--ink-2)', maxWidth:540, margin:'0 0 32px', lineHeight:1.45, textWrap:'pretty'}}>
            The API that <span style={{color:'var(--ink)', fontWeight:500}}>hundreds of SaaS platforms, marketplaces and agencies</span> rely on to get review data, post replies, and generate insights from Google, Yelp, Facebook and <span className="mono" style={{color:'var(--ink)'}}>80+</span> other sites. Ship review management in days — not 18 months.
          </p>
          <div style={{display:'flex', gap:10, marginBottom:40}}>
            <Btn variant="primary">Book a demo →</Btn>
            <Btn variant="ghost">Explore API docs</Btn>
          </div>
          <div style={{display:'flex', gap:40, paddingTop:24, borderTop:'1px solid var(--rule)'}}>
            <div>
              <div className="mono" style={{fontSize:24, fontWeight:500, letterSpacing:'-0.02em', color:'var(--ink)', fontVariantNumeric:'tabular-nums'}}>300+</div>
              <div style={{fontSize:12, color:'var(--ink-3)', marginTop:4}}>Platform partners</div>
            </div>
            <div>
              <div className="mono" style={{fontSize:24, fontWeight:500, letterSpacing:'-0.02em'}}>80+</div>
              <div style={{fontSize:12, color:'var(--ink-3)', marginTop:4}}>Review sites covered</div>
            </div>
            <div>
              <div className="mono" style={{fontSize:24, fontWeight:500, letterSpacing:'-0.02em', fontVariantNumeric:'tabular-nums'}}>{count.toLocaleString()}</div>
              <div style={{fontSize:12, color:'var(--ink-3)', marginTop:4}}>Reviews synced this month</div>
            </div>
          </div>
        </div>

        {/* Live ticker / code column */}
        <div style={{position:'relative'}}>
          {variant === 'code' ? <HeroCode/> : (
          <div style={{position:'relative', height:540, borderRadius:16, border:'1px solid var(--rule)', background:'color-mix(in oklab, var(--paper-2) 50%, var(--paper))', overflow:'hidden', padding:16}}>
            <div style={{display:'flex', alignItems:'center', justifyContent:'space-between', padding:'4px 6px 12px', borderBottom:'1px dashed var(--rule-2)', marginBottom:12}}>
              <div style={{display:'flex', alignItems:'center', gap:8}}>
                <Dot c="var(--coral)"/>
                <span className="mono" style={{fontSize:12, color:'var(--ink-2)'}}>GET /v4/reviews?stream=true</span>
              </div>
              <span className="mono" style={{fontSize:11, color:'var(--ink-3)'}}>LIVE</span>
            </div>
            <Ticker/>
            <div style={{position:'absolute', left:0, right:0, bottom:0, height:120, background:'linear-gradient(to top, var(--paper), transparent)', pointerEvents:'none'}}/>
          </div>
          )}
        </div>
      </div>
    </section>
  );
};

const Ticker = () => {
  const [items, setItems] = useS1(() => REVIEWS.slice());
  useE1(()=>{
    let i = 0;
    const id = setInterval(()=>{
      setItems(prev => {
        const pool = REVIEWS;
        const next = pool[(i++) % pool.length];
        return [{...next, t:'just now'}, ...prev.slice(0,6)];
      });
    }, 2400);
    return ()=>clearInterval(id);
  },[]);
  return (
    <div style={{display:'flex', flexDirection:'column', gap:10}}>
      {items.map((r,idx)=>(
        <div key={idx+r.author+r.t} style={{
          opacity: 1 - idx*0.12,
          transform: `translateY(0)`,
          animation: idx===0?'slideIn .5s ease':undefined,
        }}>
          <ReviewCard r={r}/>
        </div>
      ))}
      <style>{`@keyframes slideIn { from { opacity:0; transform:translateY(-12px);} to {opacity:1; transform:translateY(0);} }`}</style>
    </div>
  );
};

// ---------- Partners strip ----------
const Platforms = () => {
  const partners = ['eci','Daxko','DRB','Simpro','Fishbowl','Caring','Jobber','Housecall','ServSuite','Accelo','Thryv','Kenect'];
  return (
    <section style={{padding:'56px 0', borderTop:'1px solid var(--rule)', borderBottom:'1px solid var(--rule)', background:'var(--paper-2)'}}>
      <div className="wrap">
        <div style={{display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:28}}>
          <div style={{fontSize:13, color:'var(--ink-3)', letterSpacing:'0.08em', textTransform:'uppercase', fontWeight:500}}>
            Review infrastructure trusted by leading platforms
          </div>
          <a style={{fontSize:13, color:'var(--ink-2)'}}>See all 300+ partners →</a>
        </div>
        <div style={{display:'grid', gridTemplateColumns:'repeat(6, 1fr)', gap:1, background:'var(--rule)', border:'1px solid var(--rule)', borderRadius:12, overflow:'hidden'}}>
          {partners.map(n=>(
            <div key={n} style={{background:'var(--paper)', padding:'24px 8px', display:'grid', placeItems:'center', fontSize:16, color:'var(--ink-2)', fontWeight:600, letterSpacing:'-0.015em', fontFamily:'Geist'}}>{n}</div>
          ))}
        </div>
      </div>
    </section>
  );
};

// ---------- Endpoint demo ----------
const TABS = [
  { id:'fetch', label:'Fetch reviews', method:'GET', path:'/v4/reviews',
    code:`curl https://api.reviora.com/v4/reviews \\
  -H "Authorization: Bearer sk_live_..." \\
  -d "location_id=loc_9fR2" \\
  -d "source=google,yelp,facebook" \\
  -d "since=2026-04-01"`,
    resp: {
      "data": [
        { "id":"rvw_01HZ...", "source":"google", "rating":5,
          "author":"Danielle R.", "text":"Fixed my leaky sink in…",
          "sentiment":{"score":0.91,"topics":["speed","expertise"]},
          "replied": false, "created_at":"2026-04-18T14:22:09Z" }
      ],
      "next_cursor": "eyJpZCI6InJ2d18wMUhaIn0"
    }
  },
  { id:'reply', label:'Post reply', method:'POST', path:'/v4/reviews/:id/reply',
    code:`curl https://api.reviora.com/v4/reviews/rvw_01HZ/reply \\
  -X POST \\
  -H "Authorization: Bearer sk_live_..." \\
  -H "Content-Type: application/json" \\
  -d '{
    "message": "Thanks Danielle! Glad we could get it sorted fast.",
    "publish_to": "source",
    "template_id": "tpl_thanks_5star"
  }'`,
    resp: {
      "id":"rpy_02JB...", "review_id":"rvw_01HZ...",
      "status":"published", "source":"google",
      "published_at":"2026-04-19T09:02:41Z"
    }
  },
  { id:'insights', label:'Generate insights', method:'GET', path:'/v4/insights',
    code:`curl https://api.reviora.com/v4/insights \\
  -H "Authorization: Bearer sk_live_..." \\
  -d "location_id=loc_9fR2" \\
  -d "window=90d" \\
  -d "group_by=topic"`,
    resp: {
      "window":"90d", "review_count": 1482,
      "average_rating": 4.62,
      "trending_up":   [{"topic":"speed","delta":"+18%"}, {"topic":"pricing","delta":"+11%"}],
      "trending_down": [{"topic":"wait time","delta":"-22%"}],
      "summary":"Customers increasingly praise turnaround speed; wait-time complaints falling but still top-3."
    }
  },
  { id:'webhook', label:'Subscribe webhook', method:'POST', path:'/v4/webhooks',
    code:`curl https://api.reviora.com/v4/webhooks \\
  -X POST \\
  -H "Authorization: Bearer sk_live_..." \\
  -d '{
    "url":"https://your-app.com/hooks/reviews",
    "events":["review.created","review.updated","reply.failed"],
    "locations":["loc_9fR2","loc_2tA4"]
  }'`,
    resp: {
      "id":"wh_03KC...", "secret":"whsec_••••••••••kXq",
      "events":["review.created","review.updated","reply.failed"],
      "status":"active"
    }
  }
];

const prettyJSON = (obj, indent=0) => JSON.stringify(obj, null, 2);

const Endpoint = () => {
  const [tab, setTab] = useS1('fetch');
  const t = TABS.find(x=>x.id===tab);
  return (
    <section style={{padding:'120px 0'}}>
      <div className="wrap" style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:72, alignItems:'center'}}>
        <div>
          <Pill tone="ink" style={{marginBottom:18}}>02 — The endpoint</Pill>
          <h2 style={{fontSize:'clamp(36px, 4.2vw, 56px)', lineHeight:1.02, letterSpacing:'-0.03em', margin:'0 0 20px', fontWeight:600, textWrap:'balance'}}>
            Four verbs. <span className="serif" style={{fontWeight:400}}>Every</span> review site.
          </h2>
          <p style={{fontSize:17, color:'var(--ink-2)', maxWidth:460, marginBottom:28}}>
            Stop stitching together scrapers and broken iframe widgets. One REST API, one schema, one billable unit. Built for SDKs and for duct-tape bash scripts alike.
          </p>
          <div style={{display:'flex', flexDirection:'column', gap:2, borderLeft:'2px solid var(--rule)', paddingLeft:20}}>
            {TABS.map(x=>(
              <button key={x.id} onClick={()=>setTab(x.id)} style={{
                textAlign:'left', padding:'10px 0', display:'flex', alignItems:'center', gap:12,
                color: tab===x.id?'var(--ink)':'var(--ink-3)',
              }}>
                <span className="mono" style={{fontSize:11, fontWeight:500, width:44, color: tab===x.id?'var(--shout)':'var(--ink-3)'}}>{x.method}</span>
                <span className="mono" style={{fontSize:13.5}}>{x.path}</span>
                <span style={{marginLeft:'auto', fontSize:13}}>{x.label}</span>
                {tab===x.id && <span style={{marginLeft:8, color:'var(--shout)'}}>→</span>}
              </button>
            ))}
          </div>
        </div>
        <div style={{borderRadius:14, overflow:'hidden', border:'1px solid var(--ink)', boxShadow:'0 24px 60px -30px rgba(0,0,0,0.3)'}}>
          <div style={{background:'var(--ink)', color:'var(--paper)', padding:'12px 16px', display:'flex', alignItems:'center', justifyContent:'space-between'}}>
            <div style={{display:'flex', gap:6}}>
              <span style={{width:10, height:10, borderRadius:99, background:'oklch(0.68 0.18 30)'}}/>
              <span style={{width:10, height:10, borderRadius:99, background:'oklch(0.80 0.15 85)'}}/>
              <span style={{width:10, height:10, borderRadius:99, background:'oklch(0.70 0.14 150)'}}/>
            </div>
            <span className="mono" style={{fontSize:11, opacity:0.7}}>terminal — api.reviora.com</span>
            <span style={{width:50}}/>
          </div>
          <pre className="mono" style={{margin:0, padding:'18px 20px', background:'var(--ink)', color:'var(--paper)', fontSize:12.5, lineHeight:1.7, whiteSpace:'pre-wrap', wordBreak:'break-word'}}>
{highlightShell(t.code)}
          </pre>
          <div style={{background:'oklch(0.14 0.01 250)', color:'oklch(0.78 0.02 250)', padding:'10px 20px', fontSize:11, display:'flex', justifyContent:'space-between', borderTop:'1px solid oklch(0.25 0.01 250)'}}>
            <span className="mono">← response</span>
            <span className="mono" style={{color:'oklch(0.75 0.14 150)'}}>200 OK · 138ms</span>
          </div>
          <pre className="mono" style={{margin:0, padding:'18px 20px', background:'oklch(0.12 0.01 250)', color:'oklch(0.85 0.02 250)', fontSize:12.5, lineHeight:1.7, maxHeight:280, overflow:'auto'}}>
{highlightJSON(prettyJSON(t.resp))}
          </pre>
        </div>
      </div>
    </section>
  );
};

function highlightShell(s){
  const parts = s.split(/(\s)/);
  return parts.map((p,i)=>{
    if (/^curl$/.test(p)) return <span key={i} style={{color:'oklch(0.78 0.14 150)'}}>{p}</span>;
    if (/^-[A-Za-z]+$/.test(p) || /^--/.test(p)) return <span key={i} style={{color:'oklch(0.80 0.13 85)'}}>{p}</span>;
    if (/^"/.test(p)) return <span key={i} style={{color:'oklch(0.80 0.13 30)'}}>{p}</span>;
    if (/^https?:/.test(p)) return <span key={i} style={{color:'oklch(0.75 0.14 250)'}}>{p}</span>;
    return <span key={i}>{p}</span>;
  });
}
function highlightJSON(s){
  return s.split('\n').map((line,i)=>{
    const colored = line.split(/("[^"]*":|"[^"]*"|true|false|null|-?\d+\.?\d*)/).map((tok,j)=>{
      if (/^".+":$/.test(tok)) return <span key={j} style={{color:'oklch(0.78 0.12 250)'}}>{tok}</span>;
      if (/^".*"$/.test(tok))   return <span key={j} style={{color:'oklch(0.80 0.13 30)'}}>{tok}</span>;
      if (/^(true|false|null)$/.test(tok)) return <span key={j} style={{color:'oklch(0.80 0.13 85)'}}>{tok}</span>;
      if (/^-?\d+\.?\d*$/.test(tok)) return <span key={j} style={{color:'oklch(0.78 0.14 150)'}}>{tok}</span>;
      return <span key={j}>{tok}</span>;
    });
    return <div key={i}>{colored}</div>;
  });
}

Object.assign(window, { Hero, Platforms, Endpoint, ReviewCard, Stars, SRC_COLORS, REVIEWS });
