const SECTIONS = [
  { id: "readme", Comp: ReadmeSection },
  { id: "about", Comp: AboutSection },
  { id: "experience", Comp: ExperienceSection },
  { id: "skills", Comp: SkillsSection },
  { id: "projects", Comp: ProjectsSection },
  { id: "education", Comp: EducationSection },
  { id: "contact", Comp: ContactSection },
];

const BOOT_LINES = [
  { txt: "[boot] zohaib-os v5.0.1 — kernel 24.04 LTS", c: "var(--fg-2)" },
  { txt: "[ok]   mounting filesystem...                 [DONE]", c: "var(--accent)" },
  { txt: "[ok]   loading shell, completions, $PATH...   [DONE]", c: "var(--accent)" },
  { txt: "[ok]   initialising React 18.3, TS 5.5...     [DONE]", c: "var(--accent)" },
  { txt: "[ok]   warming up the typewriter...           [DONE]", c: "var(--accent)" },
  { txt: "", c: "var(--fg-2)" },
  { txt: "type 'help' in the terminal below to explore the portfolio.", c: "var(--fn)" },
  { txt: "", c: "var(--fg-2)" },
];

function App() {
  const [tweaks, setTweak] = useTweaks(window.TWEAK_DEFAULTS);

  const [activeFile, setActiveFile] = React.useState("readme");
  const [openTabs, setOpenTabs] = React.useState(FILES.map((f) => f.id));
  const [activeActivity, setActiveActivity] = React.useState("explorer");
  const editorRef = React.useRef(null);
  const termCmdRef = React.useRef(null);

  const openTabIds = React.useMemo(
    () => openTabs.map((s) => {
      const f = FILES.find((x) => x.id === s || x.name === s);
      return f ? f.id : s;
    }).filter((id, i, a) => a.indexOf(id) === i),
    [openTabs]
  );

  // Theme application
  React.useEffect(() => {
    document.documentElement.setAttribute("data-theme", tweaks.theme || "deep");
  }, [tweaks.theme]);

  // Accent hue override
  React.useEffect(() => {
    if (typeof tweaks.accentHue !== "number") return;
    document.documentElement.style.setProperty("--accent", `oklch(0.80 0.14 ${tweaks.accentHue})`);
  }, [tweaks.accentHue]);

  // Font override
  React.useEffect(() => {
    if (!tweaks.primaryFont) return;
    document.documentElement.style.setProperty("--mono", `"${tweaks.primaryFont}", ui-monospace, monospace`);
  }, [tweaks.primaryFont]);

  // Boot screen
  const [bootVisible, setBootVisible] = React.useState(!!tweaks.boot);
  const [bootStep, setBootStep] = React.useState(0);
  React.useEffect(() => {
    if (!bootVisible) return;
    if (bootStep < BOOT_LINES.length) {
      const t = setTimeout(() => setBootStep((s) => s + 1), bootStep === 0 ? 120 : 240);
      return () => clearTimeout(t);
    } else {
      const t = setTimeout(() => setBootVisible(false), 600);
      return () => clearTimeout(t);
    }
  }, [bootVisible, bootStep]);

  // Terminal lines
  const [termLines, setTermLines] = React.useState([
    { kind: "out", text: "welcome to zohaib's portfolio shell." },
    { kind: "out", text: "type 'help' for commands. try: whoami · projects · theme paper · social · ls" },
  ]);

  const focusSection = (id) => {
    setActiveFile(id);
    setOpenTabs((prev) => prev.includes(id) ? prev : [...prev, id]);
    setTimeout(() => {
      const el = document.getElementById("sec-" + id);
      if (!el) return;
      const mq = window.matchMedia("(max-width: 760px)").matches;
      if (mq) {
        const mainEl = document.querySelector(".main");
        if (mainEl) {
          const mainRect = mainEl.getBoundingClientRect();
          const elRect = el.getBoundingClientRect();
          mainEl.scrollBy({ top: elRect.top - mainRect.top - 8, behavior: "smooth" });
        }
      } else if (editorRef.current) {
        editorRef.current.scrollTo({ top: el.offsetTop - 8, behavior: "smooth" });
      }
    }, 30);
  };

  // Scroll spy
  React.useEffect(() => {
    const getContainer = () => isMobile
      ? document.querySelector(".main")
      : editorRef.current;

    const onScroll = () => {
      const container = getContainer();
      if (!container) return;
      const containerRect = container.getBoundingClientRect();
      let current = SECTIONS[0].id;
      for (const sec of SECTIONS) {
        const el = document.getElementById("sec-" + sec.id);
        if (el) {
          const elTop = el.getBoundingClientRect().top - containerRect.top;
          if (elTop <= 80) current = sec.id;
        }
      }
      setActiveFile((prev) => prev === current ? prev : current);
    };

    const container = getContainer();
    if (!container) return;
    container.addEventListener("scroll", onScroll, { passive: true });
    return () => container.removeEventListener("scroll", onScroll);
  }, [isMobile]);

  // Keyboard: Cmd/Ctrl-K focuses terminal
  React.useEffect(() => {
    const onKey = (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") {
        e.preventDefault();
        const inp = document.querySelector(".term-input");
        if (inp) inp.focus();
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  // Dynamic line numbers
  const [lineCount, setLineCount] = React.useState(420);
  React.useEffect(() => {
    const ed = editorRef.current;
    if (!ed) return;
    const lh = parseFloat(getComputedStyle(ed).fontSize) * 1.65;
    setLineCount(Math.ceil(ed.scrollHeight / lh));
  });

  const sidebarOpen = tweaks.sidebar !== false;
  const terminalOpen = tweaks.terminal !== false;

  // Mobile detection + sheet
  const [isMobile, setIsMobile] = React.useState(() => typeof window !== "undefined" && window.matchMedia("(max-width: 760px)").matches);
  React.useEffect(() => {
    const mq = window.matchMedia("(max-width: 760px)");
    const onChange = (e) => setIsMobile(e.matches);
    mq.addEventListener ? mq.addEventListener("change", onChange) : mq.addListener(onChange);
    return () => { mq.removeEventListener ? mq.removeEventListener("change", onChange) : mq.removeListener(onChange); };
  }, []);
  const [sheetOpen, setSheetOpen] = React.useState(false);

  return (
    <React.Fragment>
      {bootVisible && (
        <div className="boot">
          {BOOT_LINES.slice(0, bootStep).map((l, i) => (
            <div className="row" key={i} style={{ color: l.c }}>{l.txt || " "}</div>
          ))}
          {bootStep === BOOT_LINES.length && (
            <div className="row" style={{ marginTop: 12, color: "var(--accent)" }}>$ launching editor<span className="caret thin" /></div>
          )}
        </div>
      )}

      <div className={`app ${sidebarOpen ? "" : "sidebar-collapsed"} ${terminalOpen ? "" : "terminal-collapsed"}`}>
        {/* TITLE BAR */}
        <div className="titlebar">
          <div className="traffic"><span></span><span></span><span></span></div>
          <div className="crumbs">
            <span>~</span> / <b>zohaib-arshad</b> / <b>portfolio</b> / <span style={{ color: "var(--accent)" }}>{(FILES.find((f) => f.id === activeFile) || {}).name || "README.md"}</span>
          </div>
          <div className="right">
            <span><span className="tk-c">⌘K</span> command</span>
            <span style={{ color: "var(--accent)" }}>● live</span>
          </div>
        </div>

        {/* ACTIVITY BAR */}
        <div className="activity">
          {[
            { id: "explorer", title: "Explorer", svg: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M3 5h6l2 2h10v12H3z"/></svg> },
            { id: "search", title: "Search", svg: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg> },
            { id: "git", title: "Source Control", svg: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="7" cy="6" r="2"/><circle cx="7" cy="18" r="2"/><circle cx="17" cy="12" r="2"/><path d="M7 8v8M9 6h4a4 4 0 0 1 4 4v0"/></svg> },
            { id: "ext", title: "Extensions", svg: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/><path d="M17.5 14v3.5H21"/></svg> },
            { id: "debug", title: "Run & Debug", svg: <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><polygon points="6 4 20 12 6 20 6 4"/></svg> },
          ].map((b) => (
            <button key={b.id} title={b.title}
              className={activeActivity === b.id ? "active" : ""}
              onClick={() => setActiveActivity(b.id)}>
              {b.svg}
            </button>
          ))}
          <div className="spacer" />
          <button title="Cycle theme" onClick={() => {
            const next = tweaks.theme === "deep" ? "paper" : tweaks.theme === "paper" ? "dracula" : "deep";
            setTweak("theme", next);
          }}>
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><circle cx="12" cy="12" r="3"/><path d="M19 12a7 7 0 0 0-.2-1.6l2-1.6-2-3.4-2.4.9a7 7 0 0 0-2.8-1.6L13 2h-4l-.6 2.7a7 7 0 0 0-2.8 1.6l-2.4-.9-2 3.4 2 1.6A7 7 0 0 0 3 12a7 7 0 0 0 .2 1.6l-2 1.6 2 3.4 2.4-.9a7 7 0 0 0 2.8 1.6L9 22h4l.6-2.7a7 7 0 0 0 2.8-1.6l2.4.9 2-3.4-2-1.6c.13-.52.2-1.06.2-1.6Z"/></svg>
          </button>
        </div>

        {/* SIDEBAR */}
        <div className="sidebar">
          <h4>
            <span>Explorer</span>
            <span className="actions">
              <span className="tk-c" style={{ fontSize: 10 }}>⌘B</span>
            </span>
          </h4>
          <div className="tree">
            <div className="folder">
              <div className="row" style={{ color: "var(--fg)" }}>
                <span className="chev">▾</span>
                <span style={{ color: "var(--warn)" }}>▸</span>
                <span className="name">zohaib-arshad/</span>
                <span className="badge">main</span>
              </div>
              <div className="children">
                <div className="row active" onClick={() => focusSection("readme")}>
                  <span className="chev" />
                  <FileIcon kind="md" />
                  <span className="name">README.md</span>
                </div>
                <div className="folder">
                  <div className="row" style={{ color: "var(--fg)" }}>
                    <span className="chev">▾</span>
                    <span style={{ color: "var(--warn)" }}>▸</span>
                    <span className="name">src/</span>
                  </div>
                  <div className="children">
                    {FILES.filter((f) => f.group === "src").map((f) => (
                      <div key={f.id}
                        className={"row" + (activeFile === f.id ? " active" : "")}
                        onClick={() => focusSection(f.id)}>
                        <span className="chev" />
                        <FileIcon kind={f.icon} />
                        <span className="name">{f.name}</span>
                      </div>
                    ))}
                  </div>
                </div>
                <div className="row" onClick={() => focusSection("contact")}>
                  <span className="chev" />
                  <FileIcon kind="sh" />
                  <span className="name">contact.sh</span>
                </div>
                <div className="row" style={{ color: "var(--fg-2)" }}>
                  <span className="chev" />
                  <FileIcon kind="md" />
                  <span className="name">resume.pdf</span>
                </div>
                <div className="row" style={{ color: "var(--fg-2)" }}>
                  <span className="chev" />
                  <span className="icon" style={{ color: "var(--fg-2)" }}>·</span>
                  <span className="name">.gitignore</span>
                </div>
                <div className="row" style={{ color: "var(--fg-2)" }}>
                  <span className="chev" />
                  <span className="icon" style={{ color: "var(--fg-2)" }}>·</span>
                  <span className="name">.zshrc</span>
                </div>
              </div>
            </div>
          </div>

          <h4 style={{ marginTop: 10 }}>Outline</h4>
          <div className="tree">
            {SECTIONS.map((s) => {
              const f = FILES.find((x) => x.id === s.id);
              return (
                <div key={s.id}
                  className={"row" + (activeFile === s.id ? " active" : "")}
                  onClick={() => focusSection(s.id)}>
                  <span className="chev" style={{ color: "var(--kw)" }}>#</span>
                  <span className="name" style={{ color: activeFile === s.id ? "var(--fg)" : "var(--fg-1)" }}>
                    {(f && f.name) || s.id}
                  </span>
                </div>
              );
            })}
          </div>

          <h4 style={{ marginTop: 10 }}>Timeline</h4>
          <div style={{ padding: "4px 14px 16px", fontSize: 11.5, color: "var(--fg-2)", lineHeight: 1.7 }}>
            <div><span className="tk-c">10m ago</span> · updated <span className="tk-s">experience.log</span></div>
            <div><span className="tk-c">1h ago</span> · refactored <span className="tk-s">skills.json</span></div>
            <div><span className="tk-c">2h ago</span> · merged <span className="tk-a">main</span></div>
            <div><span className="tk-c">today</span> · published v5.0.1</div>
          </div>
        </div>

        {/* MAIN editor */}
        <div className="main">
          <div className="tabs">
            {openTabIds.map((id) => {
              const f = FILES.find((x) => x.id === id);
              if (!f) return null;
              return (
                <div key={id} className={"tab" + (activeFile === id ? " active" : "")} onClick={() => focusSection(id)}>
                  <FileIcon kind={f.icon} />
                  <span>{f.name}</span>
                  <span className="close" onClick={(e) => { e.stopPropagation(); setOpenTabs((prev) => prev.filter((p) => {
                    const ff = FILES.find((x) => x.id === p || x.name === p);
                    return ff ? ff.id !== id : true;
                  })); }}>
                    <svg viewBox="0 0 16 16" width="11" height="11" fill="none" stroke="currentColor" strokeWidth="1.4"><path d="M3 3l10 10M13 3 3 13"/></svg>
                  </span>
                </div>
              );
            })}
            <div className="filler" />
          </div>

          <div className="editor-wrap">
            <div className={"gutter" + (tweaks.showLineNumbers ? "" : " hidden")}>
              {Array.from({ length: lineCount }).map((_, i) => <div key={i}>{i + 1}</div>)}
            </div>
            <div className="editor" ref={editorRef}>
              <div className="bg-grid" />
              <ReadmeSection />
              <AboutSection />
              <ExperienceSection />
              <SkillsSection />
              <ProjectsSection onTerm={(cmd) => termCmdRef.current && termCmdRef.current(cmd)} />
              <EducationSection />
              <ContactSection />
              <div style={{ color: "var(--comment)", fontSize: 12, marginTop: 12, paddingBottom: 40 }}>
                <span className="tk-c">// EOF — file ends here. press ⌘K to focus terminal.</span>
              </div>
            </div>
          </div>
        </div>

        {/* TERMINAL (desktop bottom panel) */}
        {!isMobile && (
        <div className="terminal">
          <div className="terminal-tabs">
            <div className="tt active">TERMINAL</div>
            <div className="tt">PROBLEMS <span style={{ background: "var(--bg-2)", padding: "1px 5px", borderRadius: 3, marginLeft: 4, fontSize: 10 }}>0</span></div>
            <div className="tt">OUTPUT</div>
            <div className="tt">DEBUG CONSOLE</div>
            <div className="right">
              <button title="Clear" onClick={() => setTermLines([])}>
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M3 6h18M8 6V4h8v2M6 6v14a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V6"/></svg>
              </button>
              <button title={terminalOpen ? "Hide terminal" : "Show terminal"} onClick={() => setTweak("terminal", !terminalOpen)}>
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M5 9l7 7 7-7"/></svg>
              </button>
            </div>
          </div>
          <Terminal
            lines={termLines}
            setLines={setTermLines}
            onCommand={termCmdRef}
            focusSection={focusSection}
            setTheme={(th) => setTweak("theme", th)}
          />
        </div>
        )}

        {/* STATUS BAR */}
        <div className="statusbar">
          <span className="seg"><span className="branch">⎇ main</span></span>
          <span className="seg" style={{ color: "var(--accent)" }}><span className="dot-g" /> 0 errors</span>
          <span className="seg">0 warnings</span>
          <span className="seg">UTF-8</span>
          <span className="seg">LF</span>
          <span className="seg">TypeScript React</span>
          <div className="right">
            <span className="seg">Ln {Math.min(lineCount, 1 + (SECTIONS.findIndex((s) => s.id === activeFile) * 47))}, Col 1</span>
            <span className="seg">Spaces: 2</span>
            <span className="seg" style={{ color: "var(--accent)" }}>● connected</span>
          </div>
        </div>
      </div>

      {/* Mobile terminal sheet + FAB */}
      {isMobile && (
        <React.Fragment>
          <button className="mobile-cmd" aria-label="Open terminal" onClick={() => setSheetOpen(true)}>$_</button>
          <div className={"sheet-backdrop" + (sheetOpen ? " open" : "")} onClick={() => setSheetOpen(false)} />
          <div className={"mobile-sheet" + (sheetOpen ? " open" : "")}>
            <div className="sheet-head">
              <span>terminal · try 'help'</span>
              <button onClick={() => setSheetOpen(false)} aria-label="Close">×</button>
            </div>
            <div className="sheet-body">
              <Terminal
                lines={termLines}
                setLines={setTermLines}
                onCommand={termCmdRef}
                focusSection={(id) => { focusSection(id); setSheetOpen(false); }}
                setTheme={(th) => setTweak("theme", th)}
              />
            </div>
          </div>
        </React.Fragment>
      )}

      <TweaksPanel title="Tweaks">
        <TweakSection label="Theme">
          <TweakRadio label="Palette" value={tweaks.theme} onChange={(v) => setTweak("theme", v)}
            options={[
              { value: "deep", label: "Deep" },
              { value: "paper", label: "Paper" },
              { value: "dracula", label: "Dusk" },
            ]} />
          <TweakSlider label="Accent hue" min={0} max={360} step={5} unit="°"
            value={tweaks.accentHue} onChange={(v) => setTweak("accentHue", v)} />
        </TweakSection>
        <TweakSection label="Type">
          <TweakSelect label="Primary font" value={tweaks.primaryFont}
            onChange={(v) => setTweak("primaryFont", v)}
            options={["JetBrains Mono", "IBM Plex Mono", "Fira Code"]} />
        </TweakSection>
        <TweakSection label="Editor">
          <TweakToggle label="Line numbers" value={!!tweaks.showLineNumbers} onChange={(v) => setTweak("showLineNumbers", v)} />
          <TweakToggle label="Sidebar" value={!!tweaks.sidebar} onChange={(v) => setTweak("sidebar", v)} />
          <TweakToggle label="Terminal" value={!!tweaks.terminal} onChange={(v) => setTweak("terminal", v)} />
          <TweakToggle label="Boot animation" value={!!tweaks.boot} onChange={(v) => setTweak("boot", v)} />
        </TweakSection>
      </TweaksPanel>
    </React.Fragment>
  );
}

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