// SYNCAI app — sections + interactivity

const { useState, useEffect, useRef } = React;

const Wordmark = ({ size = 22, accentHue = 250 }) => (
  <svg className="wordmark-glyph" width={size} height={size} viewBox="0 0 24 24" fill="none">
    <circle cx="12" cy="12" r="10" stroke={`oklch(0.55 0.18 ${accentHue})`} strokeWidth="1.2" />
    <circle cx="12" cy="12" r="3" fill={`oklch(0.55 0.18 ${accentHue})`} />
    <path d="M12 2 V6 M12 18 V22 M2 12 H6 M18 12 H22" stroke={`oklch(0.55 0.18 145)`} strokeWidth="1.2" />
    <path d="M5 5 L7.5 7.5 M16.5 16.5 L19 19 M5 19 L7.5 16.5 M16.5 7.5 L19 5" stroke={`oklch(0.55 0.18 ${accentHue})`} strokeWidth="1" opacity="0.5"/>
  </svg>
);

function Nav({ accentHue }) {
  return (
    <nav className="nav">
      <a href="#top" className="wordmark">
        <Wordmark accentHue={accentHue} />
        <span>SYNCAI</span>
        <span className="mono dim" style={{fontSize: 11, marginLeft: 4, letterSpacing: '0.06em'}}>v1.0</span>
      </a>
      <div className="nav-links">
        <a href="#verticals">Verticals</a>
        <a href="#approach">Approach</a>
        <a href="#cases">Cases</a>
        <a href="#team">Team</a>
        <a href="#careers">Careers</a>
      </div>
      <a href="#contact" className="nav-cta">Get in touch →</a>
    </nav>
  );
}

function Hero({ accentHue, tagline }) {
  const [time, setTime] = useState(() => new Date());
  useEffect(() => {
    const id = setInterval(() => setTime(new Date()), 1000);
    return () => clearInterval(id);
  }, []);
  const stamp = time.toISOString().replace('T', ' ').slice(0, 19) + 'Z';

  return (
    <section className="hero" id="top">
      <div className="container" style={{flex: 1, display: 'flex', flexDirection: 'column'}}>
        <div className="hero-grid">
          <div className="hero-headline">
            <div className="section-label">⊙ Synchronized Edge · Lab 01</div>
            <h1 className="h-display">
              Intelligence,<br/>
              synchronized<br/>
              <em>// to the edge.</em>
            </h1>
            <p className="hero-tagline">
              {tagline}
            </p>
            <div className="hero-actions">
              <a href="#verticals" className="btn btn-primary">Explore the stack <span>↘</span></a>
              <a href="#approach" className="btn">Our approach</a>
            </div>
          </div>

          <div className="hero-readout">
            <span className="readout-corner tl"/><span className="readout-corner tr"/>
            <span className="readout-corner bl"/><span className="readout-corner br"/>
            <div className="readout-head">
              <span><span className="live-dot"/>LIVE · neuro-symbolic inference</span>
              <span>STREAM_ID 0xA17F</span>
            </div>
            <div className="readout-canvas-wrap">
              <HeroCanvas accentHue={accentHue} />
            </div>
            <div className="readout-stats">
              <div className="readout-stat">
                <div className="readout-stat-label">Latency</div>
                <div className="readout-stat-value">31<span className="unit">ms</span></div>
              </div>
              <div className="readout-stat">
                <div className="readout-stat-label">Footprint</div>
                <div className="readout-stat-value">184<span className="unit">KB</span></div>
              </div>
              <div className="readout-stat">
                <div className="readout-stat-label">Power</div>
                <div className="readout-stat-value">64<span className="unit">mW</span></div>
              </div>
            </div>
          </div>
        </div>

        <div className="hero-foot">
          <span>{stamp}</span>
          <span>LAT 24.7136°N · LON 46.6753°E</span>
          <span>NODE-04 · primary lab</span>
          <span>Scroll ↓</span>
        </div>
      </div>
    </section>
  );
}

function Marquee() {
  const items = [
    'Applied Neuro-Symbolic Intelligence',
    'TinyML · TinyGNN · ESP32',
    'Domain-specific LLMs',
    'Predictive Digital Twins',
    'Bio-Informatics & DICOM',
    'Hardware-Aware AI',
    'Hybrid Reasoning',
    'NCAI-grade rigor',
  ];
  const all = [...items, ...items];
  return (
    <div className="marquee">
      <div className="marquee-track">
        {all.map((t, i) => (
          <span key={i}>{t}<span className="sep">◆</span></span>
        ))}
      </div>
    </div>
  );
}

function Verticals({ accentHue }) {
  const [active, setActive] = useState(0);
  const data = window.SYNCAI_DATA.verticals;
  const v = data[active];

  return (
    <section id="verticals" className="verticals">
      <div className="container">
        <div className="verticals-head">
          <div>
            <div className="section-label">02 · Technical Verticals</div>
            <h2 className="h-section">Four directions.<br/>One architectural language.</h2>
          </div>
          <p className="dim-2" style={{maxWidth: 360, fontSize: 14}}>
            Every vertical we work in shares the same backbone: hardware-aware design, hybrid reasoning, and a refusal to wrap somebody else's model.
          </p>
        </div>

        <div className="verticals-grid">
          <div className="vertical-tabs">
            {data.map((d, i) => (
              <button key={d.id} className={`vertical-tab ${i === active ? 'active' : ''}`} onClick={() => setActive(i)}>
                <span className="tab-num">0{i + 1} / 04</span>
                <span className="tab-name">{d.name}</span>
              </button>
            ))}
          </div>

          <div className="vertical-panel" key={v.id}>
            <div className="vertical-panel-head">
              <h3 className="h-section">{v.headline}</h3>
              <span className="essence">◆ {v.essence}</span>
            </div>
            <p className="desc">{v.desc}</p>

            <div className="vertical-bullets">
              {v.bullets.map(([k, val]) => (
                <div key={k} className="vertical-bullet">
                  <div className="bk">{k}</div>
                  <div className="bv">{val}</div>
                </div>
              ))}
            </div>

            <div className="vertical-spec">
              {v.spec.map(([k, val]) => (
                <div key={k}><span>{k}_</span><strong>{val}</strong></div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function Approach({ accentHue }) {
  const stages = window.SYNCAI_DATA.approachStages;
  const [active, setActive] = useState(0);
  const refs = useRef([]);

  useEffect(() => {
    const obs = new IntersectionObserver(
      (entries) => {
        for (const e of entries) {
          if (e.isIntersecting) {
            const idx = parseInt(e.target.dataset.idx);
            if (!isNaN(idx)) setActive(idx);
          }
        }
      },
      { rootMargin: '-40% 0px -40% 0px', threshold: 0 }
    );
    refs.current.forEach((el) => el && obs.observe(el));
    return () => obs.disconnect();
  }, []);

  return (
    <section id="approach" className="approach">
      <div className="container">
        <div style={{marginBottom: 64}}>
          <div className="section-label">03 · The Method</div>
          <h2 className="h-section">From the device up.<br/>Never from the API down.</h2>
        </div>

        <div className="approach-grid">
          <div>
            <div className="approach-sticky">
              <div className="approach-diagram">
                <div className="diagram-label">Method · stage {String(active + 1).padStart(2, '0')} of 04</div>
                <ApproachCanvas stage={active} accentHue={accentHue} />
                <div className="diagram-stage-label">{stages[active].step}</div>
              </div>
            </div>
          </div>

          <div className="approach-stages">
            {stages.map((s, i) => (
              <div
                key={i}
                ref={(el) => (refs.current[i] = el)}
                data-idx={i}
                className={`approach-stage ${i === active ? 'active' : ''}`}
              >
                <div className="step">{s.step}</div>
                <h3>{s.title}</h3>
                <p>{s.body}</p>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

function Cases({ accentHue }) {
  const data = window.SYNCAI_DATA.cases;
  const [open, setOpen] = useState(null);
  return (
    <section id="cases">
      <div className="container">
        <div className="verticals-head">
          <div>
            <div className="section-label">04 · Field Deployments</div>
            <h2 className="h-section">Cases. Not pilots.</h2>
          </div>
          <p className="dim-2" style={{maxWidth: 360, fontSize: 14}}>
            Every project ships to production. Every result is measured against operator-grade KPIs, not benchmark leaderboards.
          </p>
        </div>

        <div className="cases-grid">
          {data.map((c) => (
            <div key={c.id} className={`case-card ${c.span}`} onClick={() => setOpen(c)}>
              <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center'}}>
                <span className="case-id">{c.id}</span>
                <span className="case-id">↗</span>
              </div>
              <div className="case-thumb"><CaseThumb kind={c.thumb} accentHue={accentHue} /></div>
              <div className="case-title">{c.title}</div>
              <div className="case-meta">
                {c.meta.map(([k, v]) => (
                  <div key={k}><span>{k}</span><strong>{v}</strong></div>
                ))}
              </div>
              <div className="case-tags">
                {c.tags.map((t) => <span key={t} className="case-tag">{t}</span>)}
              </div>
            </div>
          ))}
        </div>
        {open && <CaseModal c={open} onClose={() => setOpen(null)} accentHue={accentHue} />}
      </div>
    </section>
  );
}

function CaseModal({ c, onClose, accentHue }) {
  useEffect(() => {
    const k = (e) => e.key === 'Escape' && onClose();
    window.addEventListener('keydown', k);
    document.body.style.overflow = 'hidden';
    return () => { window.removeEventListener('keydown', k); document.body.style.overflow = ''; };
  }, [onClose]);
  return (
    <div onClick={onClose} style={{position: 'fixed', inset: 0, background: 'oklch(0.13 0.012 250 / 0.5)', backdropFilter: 'blur(8px)', zIndex: 100, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 32}}>
      <div onClick={(e) => e.stopPropagation()} style={{background: 'var(--bg)', border: '1px solid var(--line)', borderRadius: 4, maxWidth: 880, width: '100%', maxHeight: '85vh', overflow: 'auto', padding: 40}}>
        <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24}}>
          <span className="mono dim" style={{fontSize: 11, letterSpacing: '0.08em'}}>{c.id} · CASE STUDY</span>
          <button onClick={onClose} className="mono" style={{fontSize: 18, color: 'var(--ink-2)'}}>✕</button>
        </div>
        <h2 className="h-section" style={{fontSize: 36, marginBottom: 24}}>{c.title}</h2>
        <div className="case-thumb" style={{height: 220, marginBottom: 32}}><CaseThumb kind={c.thumb} accentHue={accentHue} /></div>
        <div style={{display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 24, marginBottom: 32, paddingBottom: 24, borderBottom: '1px solid var(--line)'}}>
          {c.meta.map(([k, v]) => (
            <div key={k}>
              <div className="mono dim" style={{fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 6}}>{k}</div>
              <div style={{fontSize: 22, fontWeight: 500}}>{v}</div>
            </div>
          ))}
        </div>
        <h3 style={{fontSize: 14, marginBottom: 12, fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--accent)'}}>BRIEF</h3>
        <p className="dim-2" style={{marginBottom: 24, lineHeight: 1.6}}>{c.brief}</p>
        <h3 style={{fontSize: 14, marginBottom: 12, fontFamily: 'JetBrains Mono, monospace', letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--accent)'}}>OUTCOME</h3>
        <p className="dim-2" style={{marginBottom: 24, lineHeight: 1.6}}>{c.outcome}</p>
        <div className="case-tags">{c.tags.map((t) => <span key={t} className="case-tag">{t}</span>)}</div>
      </div>
    </div>
  );
}

function Team() {
  const data = window.SYNCAI_DATA.team;
  return (
    <section id="team">
      <div className="container">
        <div className="verticals-head">
          <div>
            <div className="section-label">05 · The People</div>
            <h2 className="h-section">Engineers, clinicians,<br/>jurists, mariners.</h2>
          </div>
          <p className="dim-2" style={{maxWidth: 360, fontSize: 14}}>
            We hire across disciplines because edge intelligence is a discipline-spanning problem. Domain expertise sits inside the team, not behind a consulting wall.
          </p>
        </div>

        <div className="team-grid">
          {data.map((p) => (
            <div key={p.name} className="team-card">
              <div className="team-avatar" data-init={p.init} />
              <div className="team-name">{p.name}</div>
              <div className="team-role">{p.role}</div>
              <div className="team-bio">{p.bio}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Careers() {
  const data = window.SYNCAI_DATA.careers;
  const [open, setOpen] = useState(null);
  return (
    <section id="careers" style={{background: 'var(--bg-2)', borderTop: '1px solid var(--line)', borderBottom: '1px solid var(--line)'}}>
      <div className="container">
        <div className="verticals-head">
          <div>
            <div className="section-label">06 · Open Roles</div>
            <h2 className="h-section">Build the next layer<br/>of the lab.</h2>
          </div>
          <p className="dim-2" style={{maxWidth: 360, fontSize: 14}}>
            We're a small team optimizing for depth. If you've deployed models into the field — or you've operated systems that needed them — we want to talk.
          </p>
        </div>

        <div className="careers-list">
          {data.map((c) => (
            <div key={c.id} className="career-row" onClick={() => setOpen(c)}>
              <span className="c-id">{c.id}</span>
              <span className="c-title">{c.title}</span>
              <span className="c-team">{c.team}</span>
              <span className="c-loc">{c.loc}</span>
              <span className="c-arrow">→</span>
            </div>
          ))}
        </div>
        {open && <ApplyModal role={open} onClose={() => setOpen(null)} />}
      </div>
    </section>
  );
}

function ApplyModal({ role, onClose }) {
  const [sent, setSent] = useState(false);
  useEffect(() => {
    const k = (e) => e.key === 'Escape' && onClose();
    window.addEventListener('keydown', k);
    document.body.style.overflow = 'hidden';
    return () => { window.removeEventListener('keydown', k); document.body.style.overflow = ''; };
  }, [onClose]);
  const submit = (e) => { e.preventDefault(); setSent(true); };
  return (
    <div onClick={onClose} style={{position: 'fixed', inset: 0, background: 'oklch(0.13 0.012 250 / 0.5)', backdropFilter: 'blur(8px)', zIndex: 100, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 32}}>
      <div onClick={(e) => e.stopPropagation()} style={{background: 'var(--bg)', border: '1px solid var(--line)', borderRadius: 4, maxWidth: 640, width: '100%', padding: 40}}>
        <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'start', marginBottom: 24}}>
          <div>
            <span className="mono dim" style={{fontSize: 11, letterSpacing: '0.08em'}}>{role.id} · {role.team.toUpperCase()}</span>
            <h2 style={{fontSize: 28, fontWeight: 500, letterSpacing: '-0.02em', marginTop: 8}}>{role.title}</h2>
            <span className="mono dim-2" style={{fontSize: 12}}>{role.loc}</span>
          </div>
          <button onClick={onClose} className="mono" style={{fontSize: 18, color: 'var(--ink-2)'}}>✕</button>
        </div>
        {sent ? (
          <div style={{padding: '40px 0', textAlign: 'center'}}>
            <div className="mono" style={{color: 'var(--accent-2)', fontSize: 12, letterSpacing: '0.12em', marginBottom: 12}}>● APPLICATION RECEIVED</div>
            <p className="dim-2">Thanks. We'll respond within 5 business days.</p>
          </div>
        ) : (
          <form onSubmit={submit} style={{display: 'flex', flexDirection: 'column', gap: 16}}>
            <FormField label="Name" name="name" required />
            <FormField label="Email" name="email" type="email" required />
            <FormField label="Portfolio / GitHub" name="link" />
            <FormField label="Why this role?" name="why" multiline required />
            <button type="submit" className="btn btn-primary" style={{marginTop: 8, justifyContent: 'center'}}>Submit application →</button>
          </form>
        )}
      </div>
    </div>
  );
}

function FormField({ label, name, type = 'text', multiline, required }) {
  const style = {
    background: 'var(--bg-2)', border: '1px solid var(--line)', borderRadius: 2,
    padding: '12px 14px', fontFamily: 'inherit', fontSize: 14, color: 'var(--ink)',
    outline: 'none', width: '100%', resize: 'vertical',
  };
  return (
    <label style={{display: 'flex', flexDirection: 'column', gap: 6}}>
      <span className="mono dim" style={{fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase'}}>{label}{required && ' *'}</span>
      {multiline
        ? <textarea name={name} required={required} rows={4} style={style} />
        : <input name={name} type={type} required={required} style={style} />}
    </label>
  );
}

function Contact({ contact }) {
  const [sent, setSent] = useState(false);
  const [vertical, setVertical] = useState('TinyML / Edge');
  const submit = (e) => { e.preventDefault(); setSent(true); };
  return (
    <section id="contact">
      <div className="container">
        <div className="section-label">07 · Get in touch</div>
        <h2 className="h-section">Work with the lab.</h2>

        <div className="contact-block">
          <div>
            <h3 className="h-sub" style={{maxWidth: 540, marginBottom: 20}}>
              For project inquiries, research collaboration, or vendor evaluations — write us directly.
            </h3>
            <div className="contact-meta">
              <div className="contact-meta-item">
                <div className="k">Email</div>
                <div className="v"><a href={`mailto:${contact}`} style={{color: 'inherit'}}>{contact}</a></div>
              </div>
              <div className="contact-meta-item">
                <div className="k">Region</div>
                <div className="v">South Asia · Global · Remote</div>
              </div>
              <div className="contact-meta-item">
                <div className="k">Response</div>
                <div className="v">&lt; 48h business</div>
              </div>
              <div className="contact-meta-item">
                <div className="k">PGP</div>
                <div className="v">0xA17F · on request</div>
              </div>
            </div>
          </div>
          <div style={{border: '1px solid var(--line)', padding: 28, background: 'var(--bg-2)', borderRadius: 4}}>
            <div className="mono dim" style={{fontSize: 11, letterSpacing: '0.08em', marginBottom: 16}}>// SUBMIT A BRIEF</div>
            {sent ? (
              <div style={{padding: '40px 0', textAlign: 'center'}}>
                <div className="mono" style={{color: 'var(--accent-2)', fontSize: 12, letterSpacing: '0.12em', marginBottom: 12}}>● TRANSMISSION RECEIVED</div>
                <p className="dim-2" style={{fontSize: 14}}>We'll respond within 48 business hours.</p>
              </div>
            ) : (
              <form onSubmit={submit} style={{display: 'flex', flexDirection: 'column', gap: 14}}>
                <FormField label="Name" name="name" required />
                <FormField label="Email" name="email" type="email" required />
                <label style={{display: 'flex', flexDirection: 'column', gap: 6}}>
                  <span className="mono dim" style={{fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase'}}>Vertical *</span>
                  <select value={vertical} onChange={(e) => setVertical(e.target.value)} style={{background: 'var(--bg)', border: '1px solid var(--line)', borderRadius: 2, padding: '12px 14px', fontFamily: 'inherit', fontSize: 14, color: 'var(--ink)', outline: 'none'}}>
                    <option>TinyML / Edge</option>
                    <option>LegalTech / NLP</option>
                    <option>Digital Twins</option>
                    <option>Bio-Informatics</option>
                    <option>Other</option>
                  </select>
                </label>
                <FormField label="Project brief" name="brief" multiline required />
                <button type="submit" className="btn btn-primary" style={{marginTop: 4, justifyContent: 'center'}}>Transmit →</button>
              </form>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

function Footer({ accentHue }) {
  return (
    <footer className="footer">
      <div className="footer-grid">
        <div>
          <div className="wordmark" style={{marginBottom: 14}}>
            <Wordmark accentHue={accentHue} />
            <span>SYNCAI</span>
          </div>
          <div className="footer-tag">
            Applied Neuro-Symbolic Intelligence. Edge-first. Domain-tuned. Engineered for high-consequence environments.
          </div>
        </div>
        <div>
          <h5>LAB</h5>
          <ul><li><a href="#verticals">Verticals</a></li><li><a href="#approach">Approach</a></li><li><a href="#cases">Cases</a></li></ul>
        </div>
        <div>
          <h5>COMPANY</h5>
          <ul><li><a href="#team">Team</a></li><li><a href="#careers">Careers</a></li><li><a href="#contact">Contact</a></li></ul>
        </div>
        <div>
          <h5>STATUS</h5>
          <ul>
            <li><span style={{color: 'oklch(0.55 0.18 145)'}}>● </span>All systems nominal</li>
            <li>Build 1.0 · 2026.04</li>
            <li>v1.0.0 · stable</li>
          </ul>
        </div>
      </div>
      <div className="footer-bottom">
        <span>© SYNCAI · Synchronized Edge Lab</span>
        <span>Designed for the device, not the cloud.</span>
      </div>
    </footer>
  );
}

// === Tweaks panel ===
function SyncAITweaks({ tweaks, setTweaks }) {
  return (
    <TweaksPanel title="SYNCAI · TWEAKS">
      <TweakSection title="Theme">
        <TweakRadio
          label="Mode"
          value={tweaks.theme}
          onChange={(v) => setTweaks({ theme: v })}
          options={[{value: 'light', label: 'Light lab'}, {value: 'dark', label: 'Dark lab'}]}
        />
        <TweakSlider
          label="Accent hue"
          value={tweaks.accentHue}
          onChange={(v) => setTweaks({ accentHue: v })}
          min={0} max={360} step={1}
          format={(v) => `${v}°`}
        />
      </TweakSection>

      <TweakSection title="Layout">
        <TweakRadio
          label="Density"
          value={tweaks.density}
          onChange={(v) => setTweaks({ density: v })}
          options={[
            {value: 'compact', label: 'Compact'},
            {value: 'default', label: 'Default'},
            {value: 'spacious', label: 'Spacious'},
          ]}
        />
      </TweakSection>

      <TweakSection title="Copy">
        <TweakText
          label="Hero tagline"
          value={tweaks.tagline}
          onChange={(v) => setTweaks({ tagline: v })}
          multiline
        />
      </TweakSection>
    </TweaksPanel>
  );
}

function App() {
  const defaults = /*EDITMODE-BEGIN*/{
    "theme": "light",
    "accentHue": 250,
    "density": "default",
    "tagline": "An applied AI lab for edge intelligence and domain-specific automation. We deploy high-precision, optimized models where they matter most: at the point of data capture, inside high-consequence professional workflows."
  }/*EDITMODE-END*/;

  const [tweaks, setTweaks] = useTweaks(defaults);

  useEffect(() => {
    document.documentElement.dataset.theme = tweaks.theme;
    document.documentElement.dataset.density = tweaks.density;
  }, [tweaks.theme, tweaks.density]);

  return (
    <>
      <div className="grid-bg" />
      <div className="noise" />
      <Nav accentHue={tweaks.accentHue} />
      <Hero accentHue={tweaks.accentHue} tagline={tweaks.tagline} />
      <Marquee />
      <Verticals accentHue={tweaks.accentHue} />
      <Approach accentHue={tweaks.accentHue} />
      <Cases accentHue={tweaks.accentHue} />
      <Team />
      <Careers />
      <Contact contact="syncai.main@gmail.com" />
      <Footer accentHue={tweaks.accentHue} />
      <SyncAITweaks tweaks={tweaks} setTweaks={setTweaks} />
    </>
  );
}

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