// Top-level App: boot animation -> desktop -> windows.

const { Folder, Window, MenuBar } = window.Desktop;
const Contents = window.Contents;

const FOLDERS = [
  { id: "projects",    label: "projects",    title: "projects/", ContentKey: "projects" },
  { id: "readme",      label: "about.txt",   title: "about.txt", ContentKey: "readme" },
  { id: "resume",      label: "resume.pdf",  title: "resume.pdf", ContentKey: "resume" },
  { id: "experiments", label: "experiments", title: "experiments/", ContentKey: "experiments" },
  { id: "music",       label: "mixtapes",    title: "mixtapes.app", ContentKey: "music" },
  { id: "contact",     label: "contact",     title: "contact.card", ContentKey: "contact" },
];

const WALLPAPERS = [
  { id: "paper",   name: "cream paper" },
  { id: "grid",    name: "blueprint grid" },
  { id: "dots",    name: "dot field" },
  { id: "noise",   name: "newsprint" },
  { id: "void",    name: "void (dark)" },
];

function defaultLayout(w, h) {
  // Place folders around the central hero, leaving the middle band clear
  const slots = [
    { x: 80,            y: 90 },
    { x: 80,            y: 260 },
    { x: 80,            y: h - 200 },
    { x: w - 168,       y: 90 },
    { x: w - 168,       y: 260 },
    { x: w - 168,       y: h - 200 },
  ];
  const out = {};
  FOLDERS.forEach((f, i) => {
    const s = slots[i] || { x: 80 + (i*100), y: 90 };
    const jx = (((i * 31) % 11) - 5) * 2;
    const jy = (((i * 47) % 13) - 6) * 2;
    out[f.id] = { x: Math.round(s.x + jx), y: Math.round(s.y + jy) };
  });
  return out;
}

function Boot({ onDone }) {
  const lines = [
    "hyderfm.os v1.0.0 — booting…",
    "[ ok ] mounting /home/fahamid",
    "[ ok ] loading filesystem (6 folders, 0 regrets)",
    "[ ok ] checking caffeine levels........... HIGH",
    "[ ok ] starting window manager",
    "[ ok ] welcome.",
  ];
  const [shown, setShown] = React.useState(0);
  React.useEffect(() => {
    if (shown >= lines.length) {
      const t = setTimeout(onDone, 450);
      return () => clearTimeout(t);
    }
    const t = setTimeout(() => setShown(s => s + 1), shown === 0 ? 250 : 240);
    return () => clearTimeout(t);
  }, [shown]);

  return (
    <div style={{
      position: "fixed", inset: 0,
      background: "var(--ink)", color: "var(--paper)",
      fontFamily: "VT323, monospace",
      fontSize: 22,
      padding: "60px 60px",
      zIndex: 1000,
      lineHeight: 1.4,
    }}>
      {lines.slice(0, shown).map((l, i) => (
        <div key={i} style={{whiteSpace: "pre"}}>
          <span style={{color: "var(--accent-2)"}}>{">"} </span>{l}
        </div>
      ))}
      {shown < lines.length && (
        <div><span style={{color: "var(--accent-2)"}}>{">"} </span><span className="blink">█</span></div>
      )}
    </div>
  );
}

function Wallpaper({ kind }) {
  const styles = {
    paper: { background: "var(--paper)" },
    grid: {
      background: `var(--paper)
        linear-gradient(var(--ink) 1px, transparent 1px) 0 0 / 100% 28px,
        linear-gradient(90deg, var(--ink) 1px, transparent 1px) 0 0 / 28px 100%`,
      backgroundBlendMode: "normal",
      opacity: 1,
    },
    dots: {
      background: `var(--paper) radial-gradient(var(--ink) 1.2px, transparent 1.2px) 0 0 / 22px 22px`,
    },
    noise: {
      background: `repeating-linear-gradient(0deg, var(--paper) 0 2px, var(--paper-2) 2px 3px),
                   repeating-linear-gradient(90deg, transparent 0 2px, rgba(0,0,0,.03) 2px 3px)`,
    },
    void: { background: "#0c0a08", color: "var(--paper)" },
  };
  // For grid, use multiple layered backgrounds via shorthand
  const gridStyle = {
    background: "var(--paper)",
    backgroundImage: `linear-gradient(var(--rule) 1px, transparent 1px), linear-gradient(90deg, var(--rule) 1px, transparent 1px)`,
    backgroundSize: "32px 32px, 32px 32px",
    backgroundPosition: "0 0, 0 0",
    opacity: 1,
  };
  const s = kind === "grid" ? gridStyle : styles[kind];
  return (
    <div style={{
      position: "fixed", inset: 0, zIndex: 0,
      ...s,
    }}>
      {kind === "grid" && (
        <div style={{position: "absolute", inset: 0, background: "rgba(235,228,212,.4)"}}/>
      )}
    </div>
  );
}

function Locality() {
  return (
    <span>
    </span>
  );
}

function App() {
  const [booted, setBooted] = React.useState(() => sessionStorage.getItem("flayd.booted") === "1");
  const [layout, setLayout] = React.useState(() => {
    try {
      const saved = JSON.parse(localStorage.getItem("flayd.layout") || "null");
      if (saved) return saved;
    } catch {}
    return defaultLayout(window.innerWidth, window.innerHeight);
  });
  const [windows, setWindows] = React.useState({}); // id -> { x, y, w, h, z, opened }
  const [zTop, setZTop] = React.useState(10);
  const [wallpaper, setWallpaper] = React.useState(() => localStorage.getItem("flayd.wallpaper") || "paper");

  // Persist layout
  React.useEffect(() => { localStorage.setItem("flayd.layout", JSON.stringify(layout)); }, [layout]);
  React.useEffect(() => { localStorage.setItem("flayd.wallpaper", wallpaper); }, [wallpaper]);

  const moveFolder = React.useCallback((id, x, y) => {
    setLayout(l => ({ ...l, [id]: { x, y } }));
  }, []);

  const openWindow = React.useCallback((id) => {
    setZTop(z => z + 1);
    setWindows(w => {
      const existing = w[id];
      if (existing) {
        return { ...w, [id]: { ...existing, z: zTop + 1 } };
      }
      // Cascade new windows
      const count = Object.keys(w).length;
      const winW = Math.min(620, window.innerWidth - 80);
      const winH = Math.min(440, window.innerHeight - 120);
      const x = 120 + count * 28;
      const y = 80 + count * 28;
      return { ...w, [id]: { x, y, w: winW, h: winH, z: zTop + 1 } };
    });
  }, [zTop]);

  const focusWindow = React.useCallback((id) => {
    setZTop(z => z + 1);
    setWindows(w => w[id] ? { ...w, [id]: { ...w[id], z: zTop + 1 } } : w);
  }, [zTop]);

  const closeWindow = React.useCallback((id) => {
    setWindows(w => {
      const n = { ...w };
      delete n[id];
      return n;
    });
  }, []);

  const moveWindow = React.useCallback((id, x, y) => {
    setWindows(w => w[id] ? { ...w, [id]: { ...w[id], x, y } } : w);
  }, []);

  const resizeWindow = React.useCallback((id, ww, hh) => {
    setWindows(w => w[id] ? { ...w, [id]: { ...w[id], w: ww, h: hh } } : w);
  }, []);

  // Listen for menubar-triggered opens
  React.useEffect(() => {
    const h = (e) => openWindow(e.detail);
    window.addEventListener("os:open", h);
    return () => window.removeEventListener("os:open", h);
  }, [openWindow]);

  const shuffle = () => {
    const padX = 70, padY = 70;
    const next = {};
    for (const f of FOLDERS) {
      next[f.id] = {
        x: Math.round(padX + Math.random() * (window.innerWidth - padX*2 - 88)),
        y: Math.round(padY + Math.random() * (window.innerHeight - padY*2 - 100)),
      };
    }
    setLayout(next);
  };

  const onBootDone = () => {
    sessionStorage.setItem("flayd.booted", "1");
    setBooted(true);
  };

  return (
    <div style={{
      position: "fixed", inset: 0,
      color: wallpaper === "void" ? "var(--paper)" : "var(--ink)",
    }}>
      <Wallpaper kind={wallpaper}/>

      {/* Desktop body */}
      <div style={{position: "absolute", inset: 0, paddingTop: 28, zIndex: 1}}>
        {/* Centered hero: name + image (like the reference) */}
        <div style={{
          position: "absolute",
          left: "50%", top: "50%",
          transform: "translate(-50%, -50%)",
          textAlign: "center",
          pointerEvents: "none",
          width: "min(620px, 60vw)",
          color: wallpaper === "void" ? "var(--paper)" : "var(--ink)",
        }}>
          <div style={{
            fontFamily: "'Bodoni Moda', 'Didot', 'Times New Roman', serif",
            fontStyle: "italic",
            fontWeight: 700,
            fontSize: "clamp(36px, 5.6vw, 72px)",
            letterSpacing: ".01em",
            lineHeight: 1,
            marginBottom: 22,
            textTransform: "uppercase",
          }}>Fahamid Hyder</div>
          <div style={{
            position: "relative",
            border: wallpaper === "void" ? "1px solid #2a2a2a" : "1.5px solid var(--ink)",
            background: wallpaper === "void" ? "#0c0a08" : "var(--paper-2)",
            boxShadow: wallpaper === "void" ? "none" : "6px 6px 0 var(--ink)",
            aspectRatio: "16 / 10",
            overflow: "hidden",
          }}>
            <img
              src="assets/hero.jpg"
              alt="Fahamid Hyder"
              onError={(e) => { e.currentTarget.style.display = "none"; e.currentTarget.nextSibling.style.display = "flex"; }}
              style={{
                display: "block",
                width: "100%", height: "100%",
                objectFit: "cover",
              }}
            />
            <div style={{
              display: "none",
              position: "absolute", inset: 0,
              alignItems: "center", justifyContent: "center",
              flexDirection: "column", gap: 8,
              fontSize: 11, color: "var(--muted)",
              textTransform: "uppercase", letterSpacing: ".15em",
              background: "repeating-linear-gradient(45deg, var(--paper) 0 8px, var(--paper-2) 8px 16px)",
            }}>
              <div style={{fontSize: 32, fontFamily: "'Bodoni Moda', serif", fontStyle: "italic", color: "var(--ink-2)"}}>FH</div>
              <div>drop your image at assets/hero.jpg</div>
            </div>
          </div>
          <div style={{
            marginTop: 16,
            fontFamily: "'Bodoni Moda', serif",
            fontStyle: "italic",
            fontSize: 13,
            color: "var(--accent)",
            letterSpacing: ".05em",
          }}>
            <Locality/>
          </div>
        </div>

        {/* Bottom-left signature */}
        <div style={{
          position: "absolute", left: 16, bottom: 14,
          fontSize: 10, color: wallpaper === "void" ? "rgba(235,228,212,.5)" : "var(--muted)",
          maxWidth: 240, lineHeight: 1.5, pointerEvents: "none",
        }}>
          ◇ drag a folder to move it. click to open.<br/>
          ◇ try the <span style={{color: wallpaper === "void" ? "var(--accent-2)" : "var(--accent)"}}>view ▸</span> menu for wallpapers.
        </div>

        {/* Bottom-right stamp */}
        <div style={{
          position: "absolute", right: 16, bottom: 14,
          fontSize: 10, color: wallpaper === "void" ? "rgba(235,228,212,.5)" : "var(--muted)",
          textAlign: "right", lineHeight: 1.5, pointerEvents: "none",
        }}>
          {/* nothing here yet, just a grid coordinate */}
          loc 53.51°N · 8.85°W<br/>
          build #{new Date().getFullYear()}.{String(new Date().getMonth()+1).padStart(2,"0")}.{String(new Date().getDate()).padStart(2,"0")}
        </div>

        {/* Folders */}
        {FOLDERS.map(f => (
          <Folder
            key={f.id}
            id={f.id}
            label={f.label}
            x={layout[f.id]?.x ?? 80}
            y={layout[f.id]?.y ?? 80}
            isOpen={!!windows[f.id]}
            onMove={moveFolder}
            onOpen={openWindow}
          />
        ))}

        {/* Windows */}
        {FOLDERS.map(f => {
          const w = windows[f.id];
          if (!w) return null;
          const C = Contents[f.ContentKey];
          return (
            <Window
              key={f.id}
              id={f.id}
              title={f.title}
              x={w.x} y={w.y} w={w.w} h={w.h} z={w.z}
              onFocus={focusWindow}
              onClose={closeWindow}
              onMove={moveWindow}
              onResize={resizeWindow}
            >
              <C/>
            </Window>
          );
        })}
      </div>

      <MenuBar
        wallpaper={wallpaper}
        setWallpaper={setWallpaper}
        wallpapers={WALLPAPERS}
        onShuffle={shuffle}
      />

      {!booted && <Boot onDone={onBootDone}/>}
    </div>
  );
}

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