// ═══════════════════════════════════════════════════════════════════
//  UsaUsa AI — main app shell
// ═══════════════════════════════════════════════════════════════════

const { useState, useEffect, useRef } = React;
const COPY = window.COPY;
const HeroScene = window.HeroScene;
const TweaksPanel = window.TweaksPanel;
const useTweaks = window.useTweaks;
const TweakSection = window.TweakSection;
const TweakRadio = window.TweakRadio;
const TweakSlider = window.TweakSlider;
const TweakColor = window.TweakColor;
const TweakToggle = window.TweakToggle;

// ── Top chrome
function TopBar({ lang, setLang, tab, setTab, t, theme, setTheme }){
  const tabs = [
    ['home',     t.nav.home],
    ['vision',   t.nav.vision],
    ['tech',     t.nav.tech],
    ['business', t.nav.business],
    ['team',     t.nav.team],
    ['contact',  t.nav.contact],
  ];
  return (
    <header className="topbar">
      <div className="topbar-row">
        <Logo />
        <nav className="tabs" aria-label="Sections">
          {tabs.map(([id, label], i) => (
            <button
              key={id}
              className={'tab' + (tab === id ? ' on' : '')}
              onClick={() => setTab(id)}
            >
              <span className="tab-idx">{String(i).padStart(2,'0')}</span>
              <span className="tab-label">{label}</span>
            </button>
          ))}
        </nav>
        <div className="lang">
          <button className={'lang-btn' + (lang==='ja'?' on':'')} onClick={() => setLang('ja')}>JA</button>
          <span className="lang-sep">/</span>
          <button className={'lang-btn' + (lang==='en'?' on':'')} onClick={() => setLang('en')}>EN</button>
          <button
            className="theme-btn"
            onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}
            title={theme === 'dark' ? 'Switch to light' : 'Switch to dark'}
          >
            {theme === 'dark' ? '☾' : '☀'}
          </button>
        </div>
      </div>
      <div className="topbar-meta">
        <span>N 35.6762° / E 139.6503°</span>
        <span className="dot" />
        <span>TOKYO · {nowStr()}</span>
      </div>
    </header>
  );
}

function Logo(){
  return (
    <div className="logo">
      <div className="logo-mark" aria-hidden="true">
        {/* simple geometric mark: moon crescent + bunny head silhouette */}
        <svg viewBox="0 0 40 40" width="32" height="32">
          <circle cx="20" cy="20" r="14" fill="none" stroke="currentColor" strokeWidth="1"/>
          <circle cx="24" cy="18" r="11" fill="var(--bg)" />
          {/* tiny bunny head */}
          <g stroke="currentColor" strokeWidth="1" fill="none">
            <ellipse cx="14" cy="26" rx="3.2" ry="2.4"/>
            <line x1="12.8" y1="24" x2="12.2" y2="20"/>
            <line x1="15.2" y1="24" x2="15.8" y2="20"/>
          </g>
        </svg>
      </div>
      <div className="logo-text">
        <div className="logo-en">USAUSA AI</div>
        <div className="logo-ja">うさうさAI株式会社</div>
      </div>
    </div>
  );
}

function nowStr(){
  const d = new Date();
  const pad = n => String(n).padStart(2,'0');
  return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
}

// ── Hero panel (HOME)
function Hero({ t }){
  return (
    <section className="hero" data-screen-label="01 Home">
      <div className="hero-text">
        <div className="chip">{t.chip}</div>
        <h1 className="slogan">
          <span className="slogan-main">{t.slogan_main}</span>
          {t.slogan_quote && <><br/><span className="slogan-quote">{t.slogan_quote}</span></>}
          {t.slogan_tail && <span className="slogan-main">{t.slogan_tail}</span>}
        </h1>
        <div className="slogan-sub">{t.slogan_sub}</div>
        <p className="intro">{t.intro}</p>
        <div className="cta-row">
          <button className="cta primary">
            <span>{t.cta2}</span>
            <span className="cta-arrow">→</span>
          </button>
          <button className="cta">
            <span>{t.cta}</span>
            <span className="cta-arrow">↓</span>
          </button>
        </div>
      </div>
      <div className="hero-corners">
        <span>+</span><span>+</span><span>+</span><span>+</span>
      </div>
    </section>
  );
}

// ── Vision tab
function Vision({ t }){
  const v = t.vision;
  return (
    <Pane kicker={v.kicker} title={v.title} titleEn={v.titleEn} screenLabel="02 Vision">
      <p className="lead">{v.lead}</p>
      <div className="pillars">
        {v.pillars.map(p => (
          <div className="pillar" key={p.n}>
            <div className="pillar-n">{p.n}</div>
            <div className="pillar-t">{p.t}</div>
            <div className="pillar-d">{p.d}</div>
          </div>
        ))}
      </div>
    </Pane>
  );
}

// ── Tech tab
function Tech({ t }){
  const v = t.tech;
  return (
    <Pane kicker={v.kicker} title={v.title} titleEn={v.titleEn} screenLabel="03 Technology">
      <p className="lead">{v.lead}</p>

      <div className="tech-grid">
        {v.cards.map(c => (
          <article className="tech-card" key={c.tag}>
            <header className="tech-card-head">
              <div className="tech-tag">{c.tag}</div>
              <div className="tech-card-num">{c.tag.replace('T-','')}</div>
            </header>
            <SpecDiagram tag={c.tag}/>
            <h3 className="tech-title">{c.t}</h3>
            <p className="tech-desc">{c.d}</p>
            <div className="tech-spec">
              {c.spec.map(s => <div className="tech-spec-row" key={s}><span>›</span>{s}</div>)}
            </div>
          </article>
        ))}
      </div>
    </Pane>
  );
}

// little inline SVG diagrams per tech card
function SpecDiagram({ tag }){
  if (tag === 'T-01') return (
    <svg viewBox="0 0 200 80" className="spec-svg">
      <rect x="6"  y="22" width="36" height="36" fill="none" stroke="currentColor"/>
      <text x="24" y="45" textAnchor="middle" fontSize="9" fill="currentColor">VIDEO</text>
      <line x1="44" y1="40" x2="76" y2="40" stroke="currentColor" strokeDasharray="2 2"/>
      <polygon points="80,36 80,44 88,40" fill="currentColor"/>
      <g fill="none" stroke="currentColor">
        <polygon points="120,18 156,30 156,58 120,70 84,58 84,30"/>
        <line x1="120" y1="18" x2="120" y2="70"/>
        <line x1="84" y1="30" x2="156" y2="30"/>
        <line x1="84" y1="58" x2="156" y2="58"/>
      </g>
      <text x="120" y="78" textAnchor="middle" fontSize="9" fill="currentColor">3D SCENE</text>
    </svg>
  );
  if (tag === 'T-02') return (
    <svg viewBox="0 0 200 80" className="spec-svg">
      <g fill="none" stroke="currentColor">
        <circle cx="40" cy="40" r="22"/>
        <circle cx="40" cy="40" r="3" fill="currentColor"/>
        <text x="40" y="76" textAnchor="middle" fontSize="9">GAZE / 3D POS</text>
        <line x1="64" y1="40" x2="120" y2="40" strokeDasharray="2 2"/>
        <rect x="120" y="20" width="70" height="40"/>
        <text x="155" y="44" textAnchor="middle" fontSize="9">LLM</text>
        <text x="155" y="76" textAnchor="middle" fontSize="9">CONTEXT</text>
      </g>
    </svg>
  );
  return (
    <svg viewBox="0 0 200 80" className="spec-svg">
      <g fill="none" stroke="currentColor">
        <rect x="6" y="14" width="60" height="52"/>
        <text x="36" y="44" textAnchor="middle" fontSize="9">DASHCAM</text>
        <line x1="68" y1="40" x2="100" y2="40" strokeDasharray="2 2"/>
        <polygon points="100,36 100,44 108,40" fill="currentColor"/>
        {[0,1,2,3].map(i => <circle key={i} cx={130 + i*16} cy={40} r="4"/>)}
        <text x="162" y="76" textAnchor="middle" fontSize="9">CO₂ MAP</text>
      </g>
    </svg>
  );
}

// ── Business tab
function Business({ t }){
  const v = t.business;
  return (
    <Pane kicker={v.kicker} title={v.title} titleEn={v.titleEn} screenLabel="04 Business">
      <p className="lead">
        {v.lead || (t === COPY.ja
          ? '空間知能エンジンを核に、駐車場・施設案内・GXの3領域から実装を開始する。'
          : 'Three live applications, each powered by the same spatial-intelligence engine.')}
      </p>

      {/* index strip */}
      <div className="biz-index">
        {v.cards.map((c, i) => (
          <div className="biz-index-cell" key={i}>
            <div className="biz-index-n">0{i+1}</div>
            <div className="biz-index-t">{c.t}</div>
            <div className="biz-index-s">{c.sub}</div>
          </div>
        ))}
      </div>

      <div className="biz-list">
        {v.cards.map((c, i) => (
          <article className="biz-row" key={i}>
            <div className="biz-num">
              <div className="biz-num-big">0{i+1}</div>
              <div className="biz-num-line"/>
            </div>
            <div className="biz-fig">
              <BizPlaceholder idx={i}/>
              <div className="biz-fig-cap">FIG.{i+1} — {c.sub.toUpperCase()}</div>
            </div>
            <div className="biz-body">
              <div className="biz-n">{c.n}</div>
              <h3 className="biz-t">{c.t}</h3>
              <div className="biz-sub">{c.sub}</div>
              <p className="biz-d">{c.d}</p>
              <ul className="biz-bullets">
                {c.bullets.map(b => <li key={b}><span className="bullet-mark">▸</span>{b}</li>)}
              </ul>
            </div>
          </article>
        ))}
      </div>
    </Pane>
  );
}

// abstract wireframe imagery per business
function BizPlaceholder({ idx }){
  if (idx === 0) return (
    <svg viewBox="0 0 240 160" className="biz-svg">
      <g fill="none" stroke="currentColor">
        {/* parking grid */}
        {Array.from({length:6}).map((_,i) => <line key={i} x1={20+i*36} y1="30" x2={20+i*36} y2="130"/>)}
        <line x1="20" y1="30"  x2="200" y2="30"/>
        <line x1="20" y1="80"  x2="200" y2="80"/>
        <line x1="20" y1="130" x2="200" y2="130"/>
        {/* car */}
        <rect x="30" y="40"  width="22" height="34" rx="3"/>
        <rect x="103" y="92" width="22" height="34" rx="3"/>
        <rect x="139" y="40" width="22" height="34" rx="3" strokeDasharray="3 2"/>
        {/* scan */}
        <circle cx="115" cy="30" r="4"/>
        <line x1="115" y1="30" x2="115" y2="130" strokeDasharray="2 4" opacity=".5"/>
      </g>
    </svg>
  );
  if (idx === 1) return (
    <svg viewBox="0 0 240 160" className="biz-svg">
      <g fill="none" stroke="currentColor">
        {/* phone with AR */}
        <rect x="80" y="20" width="80" height="120" rx="8"/>
        <rect x="92" y="34" width="56" height="80"/>
        {/* AR hud */}
        <line x1="92" y1="50" x2="148" y2="50" strokeDasharray="2 2"/>
        <line x1="92" y1="80" x2="148" y2="80" strokeDasharray="2 2"/>
        <circle cx="120" cy="65" r="8"/>
        <circle cx="120" cy="65" r="14" opacity=".4"/>
        <text x="120" y="128" fontSize="8" textAnchor="middle" fill="currentColor">AR</text>
      </g>
    </svg>
  );
  return (
    <svg viewBox="0 0 240 160" className="biz-svg">
      <g fill="none" stroke="currentColor">
        {/* city map with hot spots */}
        <line x1="20" y1="40" x2="220" y2="40"/>
        <line x1="20" y1="80" x2="220" y2="80"/>
        <line x1="20" y1="120" x2="220" y2="120"/>
        <line x1="60" y1="20" x2="60" y2="140"/>
        <line x1="120" y1="20" x2="120" y2="140"/>
        <line x1="180" y1="20" x2="180" y2="140"/>
        <circle cx="60" cy="80" r="10"/>
        <circle cx="60" cy="80" r="18" opacity=".4"/>
        <circle cx="120" cy="40" r="6"/>
        <circle cx="180" cy="120" r="14"/>
        <circle cx="180" cy="120" r="22" opacity=".3"/>
      </g>
    </svg>
  );
}

// ── Team tab
function Team({ t }){
  const v = t.team;
  return (
    <Pane kicker={v.kicker} title={v.title} titleEn={v.titleEn} screenLabel="05 Team">
      <div className="team">
        <div className="team-photo" aria-hidden="true">
          <div className="team-photo-inner">
            <div className="team-photo-label">PORTRAIT · 1:1</div>
          </div>
        </div>
        <div className="team-body">
          <div className="team-name">{v.name}</div>
          <div className="team-name-en">{v.nameEn}</div>
          <div className="team-role">{v.role}</div>
          <p className="team-bio">{v.bio}</p>
          <ul className="team-cv">
            {v.cv.map(c => <li key={c}><span className="bullet-mark">›</span>{c}</li>)}
          </ul>
          <div className="team-note">{v.teamNote}</div>
        </div>
      </div>
    </Pane>
  );
}

// ── Contact tab
function Contact({ t }){
  const v = t.contact;
  return (
    <Pane kicker={v.kicker} title={v.title} titleEn={null} screenLabel="06 Contact">
      <p className="lead">{v.lead}</p>
      <div className="contact-grid">
        <div className="contact-cell">
          <div className="contact-k">EMAIL</div>
          <a href={'mailto:' + v.email} className="contact-v link">{v.email}</a>
        </div>
        <div className="contact-cell">
          <div className="contact-k">WEB</div>
          <div className="contact-v">{v.web} <span className="dim">{v.webNote}</span></div>
        </div>
        <div className="contact-cell">
          <div className="contact-k">HQ</div>
          <div className="contact-v">{v.addr}</div>
        </div>
      </div>
    </Pane>
  );
}

// ── reusable pane
function Pane({ kicker, title, titleEn, screenLabel, children }){
  return (
    <section className="pane" data-screen-label={screenLabel}>
      <div className="pane-head">
        <div className="kicker">{kicker}</div>
        <h2 className="pane-title">{title}</h2>
        {titleEn && <div className="pane-title-en">{titleEn}</div>}
      </div>
      <div className="pane-body">{children}</div>
    </section>
  );
}

// ── footer
function Foot({ t }){
  return (
    <footer className="foot">
      <div>{t.foot.legal}</div>
      <div className="foot-tag">{t.foot.tag}</div>
    </footer>
  );
}

// ═══════════════════════════════════════════════════════════════════
// App
// ═══════════════════════════════════════════════════════════════════

function App(){
  const [lang, setLang] = useState('ja');
  const [tab, setTab] = useState('home');
  const [tweaks, setTweak] = useTweaks(window.__TWEAK_DEFAULTS__);
  const t = COPY[lang];

  // tick the topbar clock
  const [, force] = useState(0);
  useEffect(() => {
    const id = setInterval(() => force(n => n+1), 1000);
    return () => clearInterval(id);
  }, []);

  // boot terminal
  const [booted, setBooted] = useState(false);
  useEffect(() => {
    const id = setTimeout(() => setBooted(true), 1400);
    return () => clearTimeout(id);
  }, []);

  return (
    <div className={'app theme-' + (tweaks.theme || 'dark')} style={{ '--accent': tweaks.accent }}>
      <SceneLayer tweaks={tweaks} />
      <Vignette />
      {tweaks.showGrid && <SafetyGrid />}
      <BootStripe booted={booted} />

      <TopBar lang={lang} setLang={setLang} tab={tab} setTab={setTab} t={t}
        theme={tweaks.theme || 'dark'}
        setTheme={v => setTweak('theme', v)}/>

      <main className="content">
        {tab === 'home'     && <Hero t={t}/>}
        {tab === 'vision'   && <Vision t={t}/>}
        {tab === 'tech'     && <Tech t={t}/>}
        {tab === 'business' && <Business t={t}/>}
        {tab === 'team'     && <Team t={t}/>}
        {tab === 'contact'  && <Contact t={t}/>}
      </main>

      <Foot t={t}/>

      <SideRail lang={lang} tab={tab} t={t}/>

      <TweaksPanel title="Tweaks">
        <TweakSection label="Theme">
          <TweakRadio label="Mode" value={tweaks.theme} options={[
            { value: 'dark',  label: 'Dark' },
            { value: 'light', label: 'Light' },
          ]} onChange={v => setTweak('theme', v)} />
        </TweakSection>
        <TweakSection label="Hero rendering">
          <TweakRadio label="Mode" value={tweaks.heroMode} options={[
            { value: 'hybrid', label: 'Hybrid' },
            { value: 'ascii', label: 'ASCII' },
            { value: 'wireframe', label: 'Wireframe' },
            { value: 'pointcloud', label: 'Pointcloud' },
            { value: 'pixel', label: 'Pixel' },
          ]} onChange={v => setTweak('heroMode', v)} />
          <TweakSlider label="Speed" value={tweaks.speed} min={0.2} max={3} step={0.1}
            onChange={v => setTweak('speed', v)}/>
          <TweakSlider label="ASCII density" value={tweaks.density} min={0.5} max={2} step={0.1}
            onChange={v => setTweak('density', v)}/>
        </TweakSection>
        <TweakSection label="Style">
          <TweakColor label="Accent" value={tweaks.accent} onChange={v => setTweak('accent', v)} />
          <TweakToggle label="Show safety grid" value={tweaks.showGrid} onChange={v => setTweak('showGrid', v)} />
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

// background scene wrapper — fixed to viewport
function SceneLayer({ tweaks }){
  // light theme always uses wireframe
  const mode = tweaks.theme === 'light' ? 'wireframe' : tweaks.heroMode;
  return (
    <div className="scene-layer">
      <HeroScene
        mode={mode}
        speed={tweaks.speed}
        density={tweaks.density}
        accent={tweaks.accent}
        theme={tweaks.theme || 'dark'}
      />
    </div>
  );
}

function Vignette(){
  return <div className="vignette" aria-hidden="true"/>;
}

function SafetyGrid(){
  // crosshair + corner marks like a viewfinder
  return (
    <div className="safety" aria-hidden="true">
      <div className="safety-x"/>
      <div className="safety-y"/>
      <span className="safety-c tl">⌐</span>
      <span className="safety-c tr">¬</span>
      <span className="safety-c bl">⌐</span>
      <span className="safety-c br">¬</span>
    </div>
  );
}

// boot animation: a stripe wipe on first load
function BootStripe({ booted }){
  return (
    <div className={'boot ' + (booted ? 'done' : '')}>
      <div className="boot-bar"/>
      <div className="boot-text">
        ▌ INITIALIZING SPATIAL VPS · LOADING CITY MESH · KEY FRAMES ✓ · LLM ATTACH ✓ · READY
      </div>
    </div>
  );
}

// vertical info rail on the right
function SideRail({ lang, tab, t }){
  const idx = ['home','vision','tech','business','team','contact'].indexOf(tab);
  return (
    <aside className="rail">
      <div className="rail-row"><span>LANG</span><b>{lang.toUpperCase()}</b></div>
      <div className="rail-row"><span>TAB</span><b>{String(idx).padStart(2,'0')} / 05</b></div>
      <div className="rail-row"><span>BUILD</span><b>2026.05</b></div>
      <div className="rail-row"><span>STATUS</span><b className="status-ok">● LIVE</b></div>
      <div className="rail-quote">
        “うさぎが月へ跳ぶように、私たちは現実空間を跳び越える。”
      </div>
    </aside>
  );
}

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