/* global React, ReactDOM, K, HUDViews, useTweaks, TweaksPanel, TweakSection, TweakColor, TweakSlider, TweakToggle */

const { useState, useEffect, useMemo, useCallback } = React;
const { HUDLanding, IdentityView, WorkView, PortfolioView, VenturesView, WritingView, StackView, ContactView } = HUDViews;

const TWEAK_DEFAULTS = {
  "accent": "#3dff7a",
  "density": 0.85,
  "glow": true,
  "scanlines": true
};

const CHARS = "01アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロ#$%&*+=<>/\\¦|}{][".split("");

function Rain({ density, accent, glow }) {
  const cols = useMemo(() => {
    const n = Math.max(8, Math.floor(48 * density));
    return Array.from({ length: n }).map((_, i) => {
      const len = 12 + ((i * 17) % 26);
      const dur = 8 + ((i * 13) % 18);
      const delay = -((i * 7) % 18);
      const left = (i / n) * 100 + (((i * 31) % 7) - 3);
      const opacity = 0.18 + ((i % 4) * 0.14);
      const size = 14 + (i % 3) * 2;
      const s = Array.from({ length: len })
        .map((_, j) => CHARS[(i * 7 + j * 5) % CHARS.length])
        .join("\n");
      return { s, dur, delay, left, opacity, size, key: `${i}-${density}` };
    });
  }, [density]);

  return (
    <div className="rain-bg" style={{ "--accent": accent }} aria-hidden>
      {cols.map((c) => (
        <pre
          key={c.key}
          className="rain-col"
          style={{
            left: `${c.left}%`,
            animationDuration: `${c.dur}s`,
            animationDelay: `${c.delay}s`,
            opacity: c.opacity,
            fontSize: c.size,
            textShadow: glow ? "0 0 6px var(--accent)" : "none",
          }}
        >{c.s}</pre>
      ))}
    </div>
  );
}

function TopBar({ view, onHome }) {
  const [time, setTime] = useState(() => fmtTime(new Date()));
  useEffect(() => {
    const id = setInterval(() => setTime(fmtTime(new Date())), 1000);
    return () => clearInterval(id);
  }, []);
  return (
    <header className="topbar mono">
      <div className="topbar-l">
        <span className="dotline" />
        <button className="brand" onClick={onHome} aria-label="home">
          <span className="brand-bracket">[</span>
          <span className="brand-name">{K.short}.dadzie</span>
          <span className="brand-bracket">]</span>
        </button>
        <span className="topbar-sep">/</span>
        <span className="topbar-view">{view === "hud" ? "HUD" : view.toUpperCase()}</span>
      </div>
      <div className="topbar-c">
        <span className="dim">SYS</span>
        <span className="accent">{K.role}</span>
      </div>
      <div className="topbar-r">
        <span className="dim">{K.location}</span>
        <span className="topbar-sep">·</span>
        <span className="accent">{time}</span>
        <span className="topbar-sep">·</span>
        <span className="status-live"><span className="pulse" />LIVE</span>
      </div>
    </header>
  );
}

function fmtTime(d) {
  const pad = (n) => String(n).padStart(2, "0");
  return `${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}:${pad(d.getUTCSeconds())} UTC`;
}

function BottomBar({ view, onHome }) {
  return (
    <footer className="bottombar mono">
      <div className="bbar-l">
        {view !== "hud" && (
          <button className="key-btn" onClick={onHome}>
            <kbd>esc</kbd> <span>back to HUD</span>
          </button>
        )}
        {view === "hud" && <span className="dim">click any panel · or press <kbd>1</kbd>–<kbd>7</kbd></span>}
      </div>
      <div className="bbar-r">
        <span><kbd>1</kbd> ident</span>
        <span><kbd>2</kbd> portfolio</span>
        <span><kbd>3</kbd> work</span>
        <span><kbd>4</kbd> ventures</span>
        <span><kbd>5</kbd> writing</span>
        <span><kbd>6</kbd> stack</span>
        <span><kbd>7</kbd> contact</span>
      </div>
    </footer>
  );
}

const VIEW_TITLES = {
  identity:  "01 · IDENTITY",
  portfolio: "02 · PORTFOLIO",
  work:      "03 · WORK",
  ventures:  "04 · VENTURES",
  writing:   "05 · WRITING",
  stack:     "06 · STACK",
  contact:   "07 · CONTACT",
};

function DetailHeader({ view, onHome }) {
  return (
    <div className="detail-head">
      <button className="back-btn mono" onClick={onHome}>← back to HUD</button>
      <div className="detail-title-row">
        <div className="mono small dim">// section</div>
        <h2 className="detail-title">{VIEW_TITLES[view]}</h2>
      </div>
    </div>
  );
}

function App() {
  const [t, setT] = useTweaks(TWEAK_DEFAULTS);
  const [view, setView] = useState("hud");
  const open = useCallback((v) => setView(v), []);
  const home = useCallback(() => setView("hud"), []);

  useEffect(() => {
    const map = { 1: "identity", 2: "portfolio", 3: "work", 4: "ventures", 5: "writing", 6: "stack", 7: "contact" };
    const onKey = (e) => {
      if (e.target && (e.target.tagName === "INPUT" || e.target.tagName === "TEXTAREA")) return;
      if (e.key === "Escape" && view !== "hud") { home(); }
      else if (map[e.key]) { setView(map[e.key]); }
      else if (e.key === "h" || e.key === "H") { home(); }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [view, home]);

  useEffect(() => {
    const main = document.querySelector(".stage");
    if (main) main.scrollTop = 0;
  }, [view]);

  useEffect(() => {
    document.documentElement.style.setProperty("--accent", t.accent);
    document.documentElement.classList.toggle("no-scanlines", !t.scanlines);
    document.documentElement.classList.toggle("no-glow", !t.glow);
  }, [t.accent, t.scanlines, t.glow]);

  return (
    <div className="screen" data-view={view}>
      <Rain density={t.density} accent={t.accent} glow={t.glow} />
      {t.scanlines && <div className="scanlines" aria-hidden />}
      <div className="vignette" aria-hidden />

      <TopBar view={view} onHome={home} />

      <main className="stage">
        <div className="stage-scroll" key={view}>
          {view === "hud" ? (
            <HUDLanding open={open} />
          ) : (
            <>
              <DetailHeader view={view} onHome={home} />
              {view === "identity"  && <IdentityView />}
              {view === "portfolio" && <PortfolioView />}
              {view === "work"      && <WorkView />}
              {view === "ventures"  && <VenturesView />}
              {view === "writing"   && <WritingView />}
              {view === "stack"     && <StackView />}
              {view === "contact"   && <ContactView />}
            </>
          )}
        </div>
      </main>

      <BottomBar view={view} onHome={home} />

      <TweaksPanel>
        <TweakSection label="rain">
          <TweakColor
            label="accent"
            value={t.accent}
            onChange={(v) => setT("accent", v)}
            options={["#3dff7a", "#19d35c", "#ffb13d", "#e8e8e8", "#3dbfff", "#ff3d6e"]}
          />
          <TweakSlider label="density" value={t.density} min={0.2} max={1.6} step={0.1} onChange={(v) => setT("density", v)} />
          <TweakToggle  label="glow"      value={t.glow}      onChange={(v) => setT("glow", v)} />
          <TweakToggle  label="scanlines" value={t.scanlines} onChange={(v) => setT("scanlines", v)} />
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

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