// Concept 1 — Single terminal window floating over a desktop.
// One big window (~95% of viewport), one shell, one command line.

const { useState: useState1, useEffect: useEffect1, useRef: useRef1 } = React;

// ──────────────────────────────────────────────────────────────────────────
// Desktop background — subtle, monochrome. A "desktop" with menubar + dock.
// ──────────────────────────────────────────────────────────────────────────
function Desktop({ time }) {
  return (
    <div className="absolute inset-0" style={{
      background:
        "radial-gradient(1200px 800px at 70% 20%, #2a2825 0%, #1a1815 55%, #0e0d0b 100%)",
    }}>
      {/* Subtle paper grain */}
      <div className="absolute inset-0 opacity-[0.07] pointer-events-none" style={{
        backgroundImage:
          "repeating-linear-gradient(0deg, #fff 0 1px, transparent 1px 3px), repeating-linear-gradient(90deg, #fff 0 1px, transparent 1px 3px)",
      }}/>
      {/* Menubar */}
      <div className="absolute top-0 left-0 right-0 h-7 flex items-center justify-between px-3 text-[11px] text-white/85 font-mono backdrop-blur-sm bg-black/30 border-b border-white/10">
        <div className="flex items-center gap-4">
          <span className="font-bold">●</span>
          <span className="font-semibold">Terminal</span>
          <span className="opacity-70">File</span>
          <span className="opacity-70">Edit</span>
          <span className="opacity-70">View</span>
          <span className="opacity-70">Window</span>
          <span className="opacity-70">Help</span>
        </div>
        <div className="flex items-center gap-4 tabular-nums">
          <span className="opacity-70">⌥</span>
          <span className="opacity-70">⏵</span>
          <span>{time}</span>
        </div>
      </div>
      {/* Desktop "icons" — minimal hint of folders */}
      <div className="absolute top-12 right-6 grid grid-cols-1 gap-4 text-white/40 text-[10px] font-mono text-center">
        {["projects", "research", "writings"].map(n => (
          <div key={n} className="flex flex-col items-center gap-1">
            <div className="w-9 h-7 border border-white/30 rounded-sm" style={{
              background:"linear-gradient(180deg, rgba(255,255,255,0.08) 0%, rgba(255,255,255,0.02) 100%)"
            }}/>
            <span>{n}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Shell pane — single, full-width, with a properly aligned command line.
// ──────────────────────────────────────────────────────────────────────────
function ShellPane({ shell, autoFocus, welcome, isMobile }) {
  const inputRef = useRef1(null);
  const scrollRef = useRef1(null);

  useEffect1(() => {
    if (autoFocus && !isMobile) inputRef.current?.focus();
  }, [autoFocus, isMobile]);

  useEffect1(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [shell.history]);

  const prompt = (
    <span className="font-mono text-[13px] flex items-baseline gap-0 shrink-0">
      <span className="text-emerald-700 font-semibold">{P.handle}@{P.host}</span>
      <span className="text-black/50">:</span>
      <span className="text-blue-700 font-semibold">{window.pathStr(shell.cwd)}</span>
      <span className="text-black/50">$&nbsp;</span>
    </span>
  );

  return (
    <div
      className="flex flex-col h-full min-h-0 bg-[#fbfaf7]"
      onClick={(e) => {
        if (isMobile) return;
        // Don't steal focus from interactive elements (links, buttons, etc.)
        if (e.target.closest("a, button, input, [role='button']")) return;
        inputRef.current?.focus({ preventScroll: true });
      }}
    >
      {/* History scroll */}
      <div ref={scrollRef} className="flex-1 min-h-0 overflow-y-auto overscroll-contain px-3 sm:px-6 py-3 sm:py-5 space-y-3 sm:space-y-4">
        {welcome}
        {shell.history.map(h => (
          <div key={h.id}>
            <div className="font-mono text-[13px] flex items-baseline gap-0">
              <span className="text-emerald-700 font-semibold">{P.handle}@{P.host}</span>
              <span className="text-black/50">:</span>
              <span className="text-blue-700 font-semibold">{window.pathStr(h.cwd)}</span>
              <span className="text-black/50">$&nbsp;</span>
              <span className="text-black">{h.cmd}</span>
            </div>
            {h.output && <div className="mt-2 ml-0 pl-0">{h.output}</div>}
          </div>
        ))}
      </div>

      {/* Sticky bottom command line */}
      <div className="border-t border-black/15 bg-white px-3 sm:px-6 py-2 sm:py-3 flex items-baseline gap-0 flex-wrap">
        {prompt}
        <div className="relative flex-1 min-w-[120px] flex items-baseline">
          <input
            ref={inputRef}
            value={shell.input}
            onChange={e => !isMobile && shell.setInput(e.target.value)}
            onKeyDown={isMobile ? undefined : shell.onKey}
            className={`w-full bg-transparent outline-none font-mono text-[13px] text-black caret-transparent relative z-10 ${isMobile ? "pointer-events-none text-black/50" : ""}`}
            spellCheck={false}
            autoComplete="off"
            placeholder={isMobile ? "Terminal input disabled on mobile" : "type a command — try help"}
            readOnly={isMobile}
            aria-disabled={isMobile}
          />
          {/* Ghost suggestion + custom blinking caret, positioned over the input */}
          <span
            aria-hidden
            className="absolute font-mono text-[13px] pointer-events-none whitespace-pre"
            style={{ left: 0 }}
          >
            <span className="invisible">{shell.input || ""}</span>
            <span className="inline-block w-[7px] h-[15px] bg-black align-text-bottom animate-blink translate-y-[2px]"></span>
            {shell.ghost && (
              <span className="text-black/30">{shell.ghost}</span>
            )}
          </span>
        </div>
        <span className={`ml-3 font-mono text-[10px] text-black/35 uppercase tracking-[0.18em] select-none whitespace-nowrap ${isMobile ? "hidden" : "hidden md:inline"}`}>
          tab ↹ complete · → accept
        </span>
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Welcome banner — shown before any command is typed.
// ──────────────────────────────────────────────────────────────────────────
function WelcomeBanner({ run, compact, isMobile, onReadableView }) {
  const ascii = [
    " █████╗ ██████╗ ████████╗██╗  ██╗██╗   ██╗██████╗",
    "██╔══██╗██╔══██╗╚══██╔══╝██║  ██║██║   ██║██╔══██╗",
    "███████║██████╔╝   ██║   ███████║██║   ██║██████╔╝",
    "██╔══██║██╔══██╗   ██║   ██╔══██║██║   ██║██╔══██╗",
    "██║  ██║██║  ██║   ██║   ██║  ██║╚██████╔╝██║  ██║",
    "╚═╝  ╚═╝╚═╝  ╚═╝   ╚═╝   ╚═╝  ╚═╝ ╚═════╝ ╚═╝  ╚═╝",
  ].join("\n");
  const quick = ["about", "projects", "skills", "experience", "contact", "help"];
  return (
    <div className={`space-y-3 sm:space-y-4 ${compact ? "pb-3 mb-3 border-b border-black/10" : ""}`}>
      <pre className="font-mono text-[7px] sm:text-[9px] md:text-[10px] leading-[1.15] text-black/85 overflow-hidden">{ascii}</pre>
      <div className="font-mono text-[11px] sm:text-[12px] text-black/70 max-w-2xl leading-relaxed">
        Welcome. This is an interactive résumé. Type a command to explore — or tap one below.
        Use <span className="text-black">↑/↓</span> for history, <span className="text-black">tab</span> to autocomplete, <span className="text-black">clear</span> to reset.
      </div>
      {isMobile ? (
        <div className="space-y-3 sm:space-y-4">
          <div className="font-mono text-[11px] sm:text-[12px] max-w-2xl leading-relaxed font-bold text-black">
            TO HAVE FULL EXPERIENCE PLEASE VISIT MY PORTFOLIO FROM A COMPUTER. HERE IS AN EASIER READABLE VERSION FOR EASY ACCESS:
          </div>
          <div className="flex justify-center">
            <button
              onClick={onReadableView}
              className="font-mono text-[12px] px-3 py-1.5 border border-black bg-white hover:bg-black hover:text-white transition-colors font-bold"
            >
              readable view ↗
            </button>
          </div>
        </div>
      ) : (
        <div className="flex flex-wrap gap-2">
          {quick.map(c => (
            <button key={c} onClick={() => run(c)}
              className="font-mono text-[12px] px-2 py-1 border border-black/40 hover:bg-black hover:text-white transition-colors">
              {c}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// The terminal window itself — chrome + traffic lights + tab bar + body.
// ──────────────────────────────────────────────────────────────────────────
function TerminalWindow({ children, title, subtitle, time, onExit }) {
  return (
    <div
      className="relative bg-[#fbfaf7] text-black flex flex-col overflow-hidden"
      style={{
        width: "min(95%, 100vw)",
        height: "min(95%, 100vh)",
        borderRadius: 10,
        boxShadow:
          "0 30px 80px rgba(0,0,0,0.55), 0 8px 20px rgba(0,0,0,0.35), 0 0 0 1px rgba(255,255,255,0.06)",
      }}
    >
      {/* Title bar */}
      <div className="h-9 shrink-0 flex items-center px-2 sm:px-3 border-b border-black/15 bg-[#ecebe6] gap-2">
        <div className="flex items-center gap-2 shrink-0">
          <button onClick={onExit} aria-label="close" title="Exit to readable view" className="w-3 h-3 rounded-full bg-[#ff5f57] hover:brightness-90 border border-black/15"></button>
          <span className="w-3 h-3 rounded-full bg-[#febc2e] border border-black/15"></span>
          <span className="w-3 h-3 rounded-full bg-[#28c840] border border-black/15"></span>
        </div>
        <div className="hidden md:flex absolute left-1/2 -translate-x-1/2 font-mono text-[12px] text-black/70 items-center gap-2">
          <span className="opacity-60">⌘</span>
          <span>{title}</span>
          <span className="text-black/30">—</span>
          <span className="text-black/50">{subtitle}</span>
        </div>
        <button
          onClick={onExit}
          className="ml-auto font-mono text-[10px] sm:text-[11px] px-2 sm:px-2.5 py-1 border border-black/30 bg-white hover:bg-black hover:text-white transition-colors flex items-center gap-1.5 whitespace-nowrap"
          title="Switch to a non-terminal version of this site"
        >
          <span>readable view</span>
          <span aria-hidden>↗</span>
        </button>
      </div>

      {/* Tab bar */}
      <div className="shrink-0 flex items-stretch border-b border-black/15 bg-[#f4f3ee] text-[10px] sm:text-[11px] font-mono overflow-hidden">
        <div className="px-2 sm:px-3 py-1.5 bg-[#fbfaf7] border-r border-black/15 flex items-center gap-2 text-black min-w-0">
          <span className="w-1.5 h-1.5 rounded-full bg-emerald-600 shrink-0"></span>
          <span className="truncate">arthur — -zsh</span>
          <span className="text-black/30 ml-1 sm:ml-2 shrink-0">×</span>
        </div>
        <div className="hidden sm:flex px-3 py-1.5 border-r border-black/10 text-black/50 items-center gap-2">+</div>
        <div className="ml-auto px-2 sm:px-3 py-1.5 text-black/40 truncate hidden sm:block">{P.location}</div>
      </div>

      {/* Body */}
      <div className="flex-1 min-h-0 flex flex-col">
        {children}
      </div>

      {/* Bottom status strip */}
      <div className="shrink-0 h-6 px-2 sm:px-3 flex items-center justify-between text-[9px] sm:text-[10px] font-mono uppercase tracking-[0.15em] sm:tracking-[0.2em] bg-[#ecebe6] border-t border-black/15 text-black/55 gap-2">
        <span className="shrink-0">● connected</span>
        <span className="truncate hidden sm:inline">{P.name} · interactive résumé · v2.6</span>
        <span className="shrink-0">UTF-8</span>
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────────────────
// Main concept component.
// ──────────────────────────────────────────────────────────────────────────
function TmuxFolio({ onExit, booting }) {
  const shell = window.useShell({ onExit });
  const [time, setTime] = useState1("");
  const [isMobile, setIsMobile] = useState1(window.matchMedia("(max-width: 512px)").matches);

  useEffect1(() => {
    const upd = () => setTime(new Date().toTimeString().slice(0, 8));
    upd();
    const id = setInterval(upd, 1000);
    return () => clearInterval(id);
  }, []);

  useEffect1(() => {
    const mq = window.matchMedia("(max-width: 512px)");
    const onChange = (e) => setIsMobile(e.matches);
    if (mq.addEventListener) mq.addEventListener("change", onChange);
    else mq.addListener(onChange);
    return () => {
      if (mq.removeEventListener) mq.removeEventListener("change", onChange);
      else mq.removeListener(onChange);
    };
  }, []);

  // Don't auto-run anything; show welcome banner instead.
  const showWelcome = shell.history.length === 0;

  return (
    <div className="absolute inset-0 flex items-center justify-center" style={{
      fontFamily: "'JetBrains Mono', ui-monospace, monospace",
    }}>
      <Desktop time={time} />

      <TerminalWindow
        title="arthur — terminal"
        subtitle={`${P.handle}@${P.host}: ~`}
        time={time}
        onExit={onExit}
      >
        <ShellPane
          shell={shell}
          autoFocus={!isMobile}
          isMobile={isMobile}
          welcome={
            <WelcomeBanner
              run={shell.run}
              compact={shell.history.length > 0}
              isMobile={isMobile}
              onReadableView={onExit}
            />
          }
        />
      </TerminalWindow>
    </div>
  );
}

window.TmuxFolio = TmuxFolio;
