// Leviyet Labs — the AI and software practice. Audits, agents, automations,
// custom software and the web/product builds that carry them.
// Hosts the three live tools (chat, 60-second audit, automation calculator).

const Labs = () => {
  const [quizStep, setQuizStep] = React.useState(0);
  const [quizAnswers, setQuizAnswers] = React.useState({});
  const [chatInput, setChatInput] = React.useState('');
  const [chatMessages, setChatMessages] = React.useState([
    { role: 'bot', text: "Hi, I'm Levi, an assistant trained on how Leviyet Labs works. Ask me anything about working with us." },
  ]);
  const [calc, setCalc] = React.useState({ team: 35, hours: 8, wage: 45 });

  const annual = Math.round(calc.team * calc.hours * calc.wage * 50 * 0.6);
  const [displayNum, setDisplayNum] = React.useState(annual);
  React.useEffect(() => {
    let raf; const start = performance.now(); const from = displayNum; const dur = 350;
    const step = (now) => {
      const p = Math.min(1, (now - start) / dur);
      const e = 1 - Math.pow(1 - p, 3);
      setDisplayNum(Math.round(from + (annual - from) * e));
      if (p < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  // eslint-disable-next-line
  }, [annual]);

  const sendChat = async () => {
    if (!chatInput.trim()) return;
    const q = chatInput.trim();
    setChatInput('');
    setChatMessages(m => [...m, { role: 'user', text: q }, { role: 'bot', text: '…', pending: true }]);
    try {
      const reply = await window.claude.complete(
        `You are Levi, friendly voice for Leviyet Labs, the AI and software practice inside Leviyet, a Toronto house of four practices (Studio, Labs, Digital, Ventures). Labs does AI audits, custom agents, automations, custom software and portals, web and product builds, training. Warm, conversational, no jargon. 2-3 sentences. User: "${q}"`
      );
      setChatMessages(m => m.filter(x => !x.pending).concat({ role: 'bot', text: reply }));
    } catch {
      setChatMessages(m => m.filter(x => !x.pending).concat({ role: 'bot', text: "Let's talk directly. Book a call below." }));
    }
  };

  const quizQs = [
    { q: 'How big is your team?', opts: ['1–10', '10–50', '50–100', '100+'] },
    { q: "Where's the time bleeding?", opts: ['Customer support', 'Internal ops', 'Content & marketing', 'Reporting & data'] },
    { q: 'Tried AI tools before?', opts: ['Just ChatGPT', 'A few SaaS tools', 'Built something custom', 'Not yet'] },
  ];
  const showResult = quizStep >= 3;

  const offers = [
    { n: '01', t: 'AI Opportunity Audit', d: 'Two weeks inside your team. We learn how the business actually runs, then point at the corners where AI pays off most, and the corners where it won\'t.', meta: ['timeline', '2 weeks'] },
    { n: '02', t: 'Agents & Automations', d: 'Internal copilots, customer-facing assistants, workflows that run themselves. Built into the tools you already use and owned by you.', meta: ['timeline', '4–8 weeks'] },
    { n: '03', t: 'Custom Software & Portals', d: 'Customer portals, ordering and credit flows, internal tools, dashboards. The software your business needs that nobody sells off the shelf.', meta: ['timeline', '6–12 weeks'] },
    { n: '04', t: 'Web & Product Builds', d: 'Sites, DTC storefronts, subscription flows, product experiences. Fast, measured, and designed with the Studio so the brand survives the build.', meta: ['timeline', '6–10 weeks'] },
    { n: '05', t: 'Marketing Systems', d: 'Content engines, lead qualification, reporting that writes itself. Built here, run by Leviyet Digital or by your team.', meta: ['timeline', '4–6 weeks'] },
    { n: '06', t: 'Training & Enablement', d: 'After we ship, your team has to live with it. Workshops, docs and office hours so the system actually gets used.', meta: ['timeline', '2–4 weeks'] },
  ];

  const cases = [
    { t: 'A 47-person CS team that finally sleeps on weekends.', m: '64% of tickets auto-resolved', s: 'B2B SaaS' },
    { t: '4,000 hours back. Same team. Same caseload.', m: '6× faster discovery review', s: 'Law firm' },
    { t: 'No-shows down by half. Front desk gets to be human again.', m: '−52% no-show rate', s: 'Multi-site clinic' },
    { t: 'RFQ turnaround from four days to six hours.', m: '180k+ documents indexed', s: 'Manufacturer' },
  ];

  const css = `
    .lb-tools { display: grid; grid-template-columns: 1.2fr 1fr 1fr; gap: 16px; }
    .lb-tool { background: #fff; border: 1px solid rgba(26,22,18,0.1); border-radius: 18px; padding: 28px; min-height: 500px; display: flex; flex-direction: column; position: relative; transition: transform 0.3s, box-shadow 0.3s; }
    .lb-tool:hover { transform: translateY(-4px); box-shadow: 0 24px 48px rgba(26,22,18,0.06); }
    .lb-tool-tag { position: absolute; top: -1px; left: 28px; padding: 5px 14px; background: #c8542a; color: #fff; font-family: 'JetBrains Mono', monospace; font-size: 10px; font-weight: 500; letter-spacing: 0.12em; border-radius: 0 0 8px 8px; text-transform: uppercase; }
    .lb-tool-title { font-family: 'Instrument Serif', serif; font-size: 28px; font-weight: 400; letter-spacing: -0.015em; margin: 32px 0 4px; line-height: 1.05; }
    .lb-tool-title em { font-style: italic; color: #c8542a; }
    .lb-tool-sub { font-size: 13px; color: #6b5d4d; margin-bottom: 24px; }
    .lb-chat-msgs { flex: 1; overflow-y: auto; display: flex; flex-direction: column; gap: 8px; margin-bottom: 12px; max-height: 320px; padding-right: 4px; }
    .lb-chat-msg { font-size: 13px; line-height: 1.5; padding: 10px 14px; border-radius: 14px; max-width: 90%; animation: lbfadein 0.3s ease-out; }
    @keyframes lbfadein { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: translateY(0); } }
    .lb-chat-msg.bot { background: #f4efe6; color: #1a1612; align-self: flex-start; }
    .lb-chat-msg.user { background: #1a1612; color: #f4efe6; align-self: flex-end; }
    .lb-chat-input { display: flex; gap: 6px; }
    .lb-chat-input input { flex: 1; background: #f4efe6; border: 1px solid rgba(26,22,18,0.1); border-radius: 12px; padding: 10px 14px; color: #1a1612; font-family: 'Inter', sans-serif; font-size: 13px; outline: none; }
    .lb-chat-input input:focus { border-color: #c8542a; }
    .lb-chat-input button { background: #c8542a; color: #fff; border: none; border-radius: 12px; padding: 0 16px; cursor: pointer; font-weight: 500; font-size: 13px; }
    .lb-quiz-q { font-family: 'JetBrains Mono', monospace; font-size: 11px; color: #6b5d4d; letter-spacing: 0.1em; margin-bottom: 12px; }
    .lb-quiz-q-text { font-family: 'Instrument Serif', serif; font-size: 22px; line-height: 1.2; margin-bottom: 20px; min-height: 56px; }
    .lb-quiz-opts { display: flex; flex-direction: column; gap: 8px; }
    .lb-quiz-opt { font-family: 'Inter', sans-serif; font-size: 14px; padding: 12px 14px; background: #f4efe6; border: 1px solid rgba(26,22,18,0.1); border-radius: 12px; cursor: pointer; text-align: left; transition: all 0.2s cubic-bezier(.2,.8,.3,1); color: #1a1612; }
    .lb-quiz-opt:hover { background: #1a1612; color: #f4efe6; border-color: #1a1612; transform: translateX(4px); }
    .lb-quiz-progress { display: flex; gap: 4px; margin-top: auto; padding-top: 16px; }
    .lb-quiz-dot { flex: 1; height: 3px; background: rgba(26,22,18,0.1); border-radius: 2px; } .lb-quiz-dot.active { background: #c8542a; }
    .lb-calc-row { display: flex; justify-content: space-between; font-size: 12px; color: #6b5d4d; margin-bottom: 4px; font-family: 'JetBrains Mono', monospace; }
    .lb-calc-row span:last-child { color: #1a1612; }
    .lb-calc-slider { width: 100%; appearance: none; height: 2px; background: rgba(26,22,18,0.1); border-radius: 2px; margin-bottom: 18px; }
    .lb-calc-slider::-webkit-slider-thumb { appearance: none; width: 16px; height: 16px; border-radius: 50%; background: #c8542a; cursor: pointer; box-shadow: 0 0 0 3px rgba(200,84,42,0.15); }
    .lb-calc-result { margin-top: auto; padding-top: 20px; border-top: 1px dashed rgba(26,22,18,0.15); }
    .lb-calc-num { font-family: 'Instrument Serif', serif; font-size: 56px; font-weight: 400; letter-spacing: -0.02em; line-height: 1; color: #c8542a; }
    .lb-calc-num em { font-style: italic; }

    .lb-cases { display: grid; grid-template-columns: repeat(2, 1fr); gap: 1px; background: rgba(26,22,18,0.12); border: 1px solid rgba(26,22,18,0.12); }
    .lb-case { background: #f4efe6; padding: 32px 28px; display: flex; flex-direction: column; gap: 12px; min-height: 220px; transition: background 0.3s; }
    .lb-case:hover { background: #ede5d6; }
    .lb-case-s { font-family: 'JetBrains Mono', monospace; font-size: 11px; letter-spacing: 0.15em; text-transform: uppercase; color: #c8542a; }
    .lb-case h3 { font-family: 'Instrument Serif', serif; font-size: 28px; line-height: 1.08; letter-spacing: -0.02em; font-weight: 400; margin: 0; }
    .lb-case b { margin-top: auto; font-family: 'JetBrains Mono', monospace; font-size: 12px; font-weight: 500; color: #1a1612; }

    @media (max-width: 1024px) {
      .lb-tools { grid-template-columns: 1fr 1fr; gap: 14px; }
      .lb-tool:first-child { grid-column: 1 / -1; min-height: auto; }
      .lb-tool { padding: 24px; min-height: 460px; }
    }
    @media (max-width: 720px) {
      .lb-tools { grid-template-columns: 1fr; }
      .lb-tool { min-height: auto; padding: 24px; }
      .lb-tool:first-child .lb-chat-msgs { max-height: 220px; }
      .lb-quiz-q-text { font-size: 19px; min-height: 48px; }
      .lb-calc-num { font-size: 44px; }
      .lb-cases { grid-template-columns: 1fr; }
      .lb-case { padding: 24px 20px; min-height: auto; }
      .lb-case h3 { font-size: 24px; }
    }
  `;

  return (
    <>
      <window.WeNav active="labs" />
      <window.WeSEO page="labs" />
      <style>{window.UNIT_CSS}{css}</style>

      <section className="we-page-hero">
        <div className="we-shead"><div className="we-shead-line"></div>Leviyet Labs</div>
        <div className="un-hero-row">
          <div>
            <h1 className="we-page-h1">AI that <em>pays its way.</em></h1>
            <p className="we-page-sub">The AI and software practice inside Leviyet. We find the corners of a business where intelligence earns its keep, build the agents and systems that live there, and the web and product builds that carry them to customers.</p>
          </div>
          <div className="un-side">
            <div><b>Toronto</b> · 43.6532° N, 79.3832° W</div>
            <div><b>Audit → build → train → stay</b></div>
            <div>Agents, automations, portals, product</div>
            <div>Built into your tools. <b>Owned by you.</b></div>
            <div>And when AI isn't the answer, <b>we say so.</b></div>
          </div>
        </div>
      </section>

      <section className="we-section">
        <div className="we-shead"><div className="we-shead-line"></div>What the lab does</div>
        <h2 className="we-stitle">Six ways in. <em>One question first:</em> does this need to exist?</h2>
        <window.UnitOffers items={offers} />
      </section>

      <section className="we-section" style={{paddingTop: 0}}>
        <div className="we-shead"><div className="we-shead-line"></div>Try the lab</div>
        <h2 className="we-stitle">Three live tools. <em>No email gate.</em></h2>
        <div className="lb-tools">
          <div className="lb-tool">
            <div className="lb-tool-tag">live</div>
            <div className="lb-tool-title">Talk to <em>our agent</em></div>
            <div className="lb-tool-sub">Trained on how the lab works.</div>
            <div className="lb-chat-msgs">
              {chatMessages.map((m, i) => <div key={i} className={`lb-chat-msg ${m.role}`}>{m.text}</div>)}
            </div>
            <div className="lb-chat-input">
              <input value={chatInput} onChange={e => setChatInput(e.target.value)} onKeyDown={e => e.key === 'Enter' && sendChat()} placeholder="Ask anything..." />
              <button onClick={sendChat}>Send</button>
            </div>
          </div>

          <div className="lb-tool">
            <div className="lb-tool-tag">60s</div>
            <div className="lb-tool-title">A 60-second <em>audit</em></div>
            <div className="lb-tool-sub">Where could AI actually help you?</div>
            {!showResult ? (
              <>
                <div className="lb-quiz-q">Q.0{quizStep + 1} / Q.03</div>
                <div className="lb-quiz-q-text">{quizQs[quizStep].q}</div>
                <div className="lb-quiz-opts">
                  {quizQs[quizStep].opts.map(o => (
                    <button key={o} className="lb-quiz-opt" onClick={() => { setQuizAnswers(a => ({ ...a, [quizStep]: o })); setQuizStep(s => s + 1); }}>{o}</button>
                  ))}
                </div>
                <div className="lb-quiz-progress">
                  {[0, 1, 2].map(i => <div key={i} className={`lb-quiz-dot ${i <= quizStep ? 'active' : ''}`} />)}
                </div>
              </>
            ) : (
              <>
                <div className="lb-quiz-q">// recommendation</div>
                <div className="lb-quiz-q-text">Highest leverage for you: <em style={{color:'#c8542a'}}>{quizAnswers[1]?.toLowerCase() || 'ops'}</em>. We'd start with a two-week audit and pick two workflows to automate first.</div>
                <button className="lb-quiz-opt" style={{marginTop:'auto'}} onClick={() => { setQuizStep(0); setQuizAnswers({}); }}>↻ Restart</button>
              </>
            )}
          </div>

          <div className="lb-tool">
            <div className="lb-tool-tag">calc</div>
            <div className="lb-tool-title">What automation <em>could be worth</em></div>
            <div className="lb-tool-sub">Drag the sliders.</div>
            <div className="lb-calc-row"><span>// team size</span><span>{calc.team}</span></div>
            <input type="range" min="5" max="100" value={calc.team} onChange={e => setCalc(v => ({ ...v, team: +e.target.value }))} className="lb-calc-slider" />
            <div className="lb-calc-row"><span>// hrs/wk manual</span><span>{calc.hours}</span></div>
            <input type="range" min="1" max="20" value={calc.hours} onChange={e => setCalc(v => ({ ...v, hours: +e.target.value }))} className="lb-calc-slider" />
            <div className="lb-calc-row"><span>// loaded $/hr</span><span>${calc.wage}</span></div>
            <input type="range" min="20" max="120" value={calc.wage} onChange={e => setCalc(v => ({ ...v, wage: +e.target.value }))} className="lb-calc-slider" />
            <div className="lb-calc-result">
              <div style={{fontFamily:'JetBrains Mono, monospace',fontSize:11,color:'#6b5d4d',letterSpacing:'0.1em'}}>// recovered per year</div>
              <div className="lb-calc-num">${(displayNum / 1000).toFixed(0)}<em>k</em></div>
            </div>
          </div>
        </div>
      </section>

      <section className="we-section" style={{paddingTop: 0}}>
        <div className="we-shead"><div className="we-shead-line"></div>Selected work</div>
        <h2 className="we-stitle">Four partnerships, <em>named in numbers.</em></h2>
        <div className="lb-cases">
          {cases.map(c => (
            <a className="lb-case" href="/work" key={c.t}>
              <div className="lb-case-s">{c.s}</div>
              <h3>{c.t}</h3>
              <b>{c.m} →</b>
            </a>
          ))}
        </div>
      </section>

      <section className="we-section" style={{paddingTop: 0}}>
        <div className="we-shead"><div className="we-shead-line"></div>How the lab works</div>
        <h2 className="we-stitle">Four moves. <em>Listen, map, build, stay.</em></h2>
        <window.UnitSteps steps={[
          { n: '01', t: 'Listen', d: "Two weeks shadowing your team. Calls, screen-shares, reading every doc you've got." },
          { n: '02', t: 'Map', d: "A written diagnosis. Where AI fits, where it doesn't, and the 90-day roadmap." },
          { n: '03', t: 'Build', d: 'Small bets first. Internal tools, customer-facing agents, portals, product.' },
          { n: '04', t: 'Stay', d: 'Monthly retainer. Watch it run, fix drift, iterate as you grow.' },
        ]} />
      </section>

      <section className="we-section" style={{paddingTop: 0}}>
        <div className="we-shead"><div className="we-shead-line"></div>// what we believe</div>
        <h2 className="we-stitle">Sometimes the best AI advice is <em>"don't use AI."</em></h2>
        <window.UnitPrinciples items={[
          { k: 'the simpler tool wins', t: 'A clearer process often beats a clever model.', d: "A one-page dashboard, one good hire, a form that asks the right question. We've turned down work where the answer was simpler than what we'd be paid to build." },
          { k: 'you own it', t: 'Built into your tools, owned by your team.', d: 'Code, configs, accounts: yours. Every engagement ends with training, not a contract you can\'t leave.' },
          { k: 'honest in numbers', t: 'We report what worked and what didn\'t.', d: 'Real metrics, plain language, every month. See the four case studies on the Work page.' },
        ]} />
      </section>

      <section className="we-section" style={{paddingTop: 0}}>
        <div className="un-cross">
          <div>
            <h3>Labs × the house: <em>built with the brand on.</em></h3>
            <p>A portal designed with the Studio looks like the brand, not like software. A content engine handed to Digital gets used every week. That's the point of a house.</p>
          </div>
          <ul>
            <li><span>01</span>Studio designs the surface, Labs builds what's under it</li>
            <li><span>02</span>Digital runs the marketing systems Labs ships</li>
            <li><span>03</span>Ventures runs our own products on the same stack</li>
            <li><span>04</span><a href="/studio">Studio →</a>&nbsp; <a href="/digital">Digital →</a>&nbsp; <a href="/ventures">Ventures →</a></li>
          </ul>
        </div>
      </section>

      <window.UnitCTA h={'Not sure where <em>to start?</em>'} p="Take the 60-second audit above, or book a 30-minute intro. No deck, no pitch." btn="Book the call →" />
      <window.WeFooter />
    </>
  );
};

window.Labs = Labs;
