import "clsx";
import { ab as ssr_context, j as attr, D as escape_html, m as bind_props, A as ensure_array_like, k as attr_class, q as clsx, l as attr_style, F as fallback, ac as store_get, ag as unsubscribe_stores, O as head } from "../../chunks/renderer.js";
import { a as appsById, C as ContentWindow, v as visibleApps } from "../../chunks/ContentWindow.js";
import { w as writable, g as get } from "../../chunks/index.js";
function onDestroy(fn) {
  /** @type {SSRContext} */
  ssr_context.r.on_destroy(fn);
}
async function tick() {
}
const commands = [
  { name: "help", description: "Lists available commands." },
  { name: "about", description: "Opens profile.exe.", appId: "profile", aliases: ["profile"] },
  { name: "cv", description: "Opens cv.core.", appId: "cv" },
  { name: "workbench", description: "Opens workbench.sys.", appId: "workbench" },
  { name: "opinions", description: "Opens opinions.safe.", appId: "opinions" },
  { name: "everwished", description: "Opens everwished.hq.", appId: "everwished" },
  { name: "charit", description: "Opens charIT mode.", appId: "charit" },
  { name: "ventures", description: "Opens ventures.map.", appId: "ventures" },
  { name: "river", description: "Opens riverbean.node.", appId: "riverbean" },
  { name: "coo", description: "Opens happycoo.treat.", appId: "happycoo" },
  { name: "media", description: "Opens media.deck.", appId: "media" },
  { name: "evidence", description: "Opens evidence.log.", appId: "evidence" },
  { name: "contact", description: "Opens contact.link.", appId: "contact" },
  { name: "terminal", description: "Opens ianOS Terminal.", appId: "terminal" },
  { name: "control", description: "Opens Control Panel.", appId: "control" },
  { name: "simple", description: "Switches to Simple Mode." },
  { name: "boot", description: "Replays the ianOS boot sequence." },
  { name: "verify", description: "Opens the evidence and verification route." },
  { name: "responsibility", description: "Displays the Responsibility by Design note." },
  { name: "no-beige", description: "Displays the No Beige declaration.", aliases: ["nobeige"] },
  { name: "gyp", description: "Displays the GypBops easter egg." },
  { name: "duck", description: "Displays the duck mode easter egg." }
];
function findCommand(input) {
  const normalised = input.trim().toLowerCase();
  return commands.find(
    (command) => command.name === normalised || command.aliases?.includes(normalised)
  );
}
const helpText = commands.map((command) => `${command.name.padEnd(14, " ")} ${command.description}`).join("\n");
function AppIcon($$renderer, $$props) {
  $$renderer.component(($$renderer2) => {
    let app = $$props["app"];
    let openApp = $$props["openApp"];
    $$renderer2.push(`<button class="app-icon" type="button"${attr("aria-label", `Open ${app.shortTitle}`)}${attr("title", app.summary)}><span class="app-icon__glyph" aria-hidden="true">${escape_html(app.icon)}</span> <span class="app-icon__label">${escape_html(app.shortTitle)}</span></button>`);
    bind_props($$props, { app, openApp });
  });
}
const defaultPreferences = {
  hasSeenBoot: false,
  simpleModePreferred: false,
  reducedMotion: false,
  theme: "ianos"
};
function readPreferences() {
  if (typeof localStorage === "undefined") return defaultPreferences;
  try {
    const saved = localStorage.getItem("ianos.preferences");
    if (!saved) {
      return {
        ...defaultPreferences,
        reducedMotion: window.matchMedia("(prefers-reduced-motion: reduce)").matches
      };
    }
    return {
      ...defaultPreferences,
      ...JSON.parse(saved),
      reducedMotion: window.matchMedia("(prefers-reduced-motion: reduce)").matches
    };
  } catch {
    return defaultPreferences;
  }
}
function createPreferencesStore() {
  const { subscribe, set, update } = writable(defaultPreferences);
  return {
    subscribe,
    initialise() {
      set(readPreferences());
    },
    updatePreference(partial) {
      update((current) => {
        const next = { ...current, ...partial };
        if (typeof localStorage !== "undefined") {
          localStorage.setItem("ianos.preferences", JSON.stringify(next));
          localStorage.setItem("hasSeenBoot", String(next.hasSeenBoot));
        }
        return next;
      });
    },
    markBootSeen() {
      this.updatePreference({ hasSeenBoot: true });
    },
    resetBoot() {
      this.updatePreference({ hasSeenBoot: false });
    },
    setTheme(theme) {
      this.updatePreference({ theme });
    }
  };
}
const preferences = createPreferencesStore();
function BootScreen($$renderer, $$props) {
  $$renderer.component(($$renderer2) => {
    let stage = "identity";
    let progress = 0;
    let statusIndex = 0;
    let statusTimer;
    const bootLines = [
      "load professional history",
      "mount creative projects",
      "initialise charity mode",
      "index questionable decisions",
      "suppress unnecessary corporate adjectives",
      "warn user: opinions detected"
    ];
    const identityWords = [
      { text: "backed by evidence.", className: "word-a" },
      { text: "verifiable.", className: "word-b" },
      { text: "proven on record.", className: "word-c" },
      { text: "authenticated.", className: "word-d" },
      {
        text: "trust comes from what can be checked.",
        className: "word-e"
      },
      { text: "independently.", className: "word-f" },
      { text: "nothing else matters.", className: "word-g" },
      { text: "proof beats promises.", className: "word-h" },
      { text: "everything else fades.", className: "word-i" }
    ];
    function goNext() {
      if (stage === "identity") {
        stage = "system";
        runSystemBoot();
        return;
      }
      finish();
    }
    function finish() {
      preferences.markBootSeen();
    }
    function onKeydown(event) {
      if (event.key === "Enter" || event.key === " ") {
        event.preventDefault();
        goNext();
      }
    }
    function runSystemBoot() {
      if (statusTimer) window.clearInterval(statusTimer);
      progress = 12;
      statusIndex = 0;
      statusTimer = window.setInterval(
        () => {
          statusIndex = Math.min(statusIndex + 1, bootLines.length - 1);
          progress = Math.min(progress + 16, 100);
          if (progress >= 100 && statusTimer) window.clearInterval(statusTimer);
        },
        520
      );
    }
    onDestroy(() => {
      if (typeof window === "undefined") return;
      window.removeEventListener("keydown", onKeydown);
      if (statusTimer) window.clearInterval(statusTimer);
    });
    $$renderer2.push(`<section class="boot-screen" aria-label="ianOS boot screen">`);
    if (stage === "identity") {
      $$renderer2.push("<!--[0-->");
      $$renderer2.push(`<div class="boot-identity" aria-live="polite"><h1>Hi, I'm <strong>Ian.</strong></h1> <div class="identity-grid" aria-label="Identity proof points"><!--[-->`);
      const each_array = ensure_array_like(identityWords);
      for (let $$index = 0, $$length = each_array.length; $$index < $$length; $$index++) {
        let word = each_array[$$index];
        $$renderer2.push(`<span${attr_class(clsx(word.className))}>${escape_html(word.text)}</span>`);
      }
      $$renderer2.push(`<!--]--></div> <p class="identity-footnote">Apologies, but cold approaches are filtered. Trust comes from established channels,
        context and things that can be checked.</p> <div class="boot-actions"><button type="button">Continue boot</button> <a href="/simple">Simple Mode</a></div></div>`);
    } else {
      $$renderer2.push("<!--[-1-->");
      $$renderer2.push(`<div class="boot-console" aria-live="polite"><p class="boot-ascii" aria-hidden="true">+-----------------------------+<br/> | ianOS                       |<br/> | useful systems // mischief  |<br/> +-----------------------------+</p> <h1>ianOS</h1> <p>Ian Barrs<br/>useful systems // useful mischief</p> <ol><!--[-->`);
      const each_array_1 = ensure_array_like(bootLines);
      for (let index = 0, $$length = each_array_1.length; index < $$length; index++) {
        let line = each_array_1[index];
        $$renderer2.push(`<li${attr_class("", void 0, { "active": index <= statusIndex })}>[${escape_html(index <= statusIndex ? "ok" : "..")}] ${escape_html(line)}</li>`);
      }
      $$renderer2.push(`<!--]--></ol> <div class="progress" aria-label="Boot progress" aria-valuemin="0" aria-valuemax="100"${attr("aria-valuenow", progress)}><span${attr_style(`width: ${progress}%`)}></span></div> <p class="boot-footer">No tracking. No autoplay. No beige.</p> <div class="boot-actions"><button type="button">Enter ianOS</button> <a href="/simple">Simple Mode</a></div></div>`);
    }
    $$renderer2.push(`<!--]--></section>`);
  });
}
function CommandPalette($$renderer, $$props) {
  $$renderer.component(($$renderer2) => {
    let matches;
    let open = fallback($$props["open"], false);
    let runCommand = $$props["runCommand"];
    let query = "";
    let inputElement;
    matches = commands.filter((command) => {
      const haystack = `${command.name} ${command.description} ${command.aliases?.join(" ") ?? ""}`.toLowerCase();
      return haystack.includes(query.trim().toLowerCase());
    });
    if (open) {
      tick().then(() => inputElement?.focus());
    }
    if (open) {
      $$renderer2.push("<!--[0-->");
      $$renderer2.push(`<div class="palette-backdrop" role="presentation"><div class="command-palette" role="dialog" aria-modal="true" aria-label="Command palette" tabindex="-1"><label for="command-search">Command</label> <input id="command-search"${attr("value", query)} placeholder="Type a command or app name" autocomplete="off"/> <div class="command-list" role="listbox"><!--[-->`);
      const each_array = ensure_array_like(matches);
      for (let $$index = 0, $$length = each_array.length; $$index < $$length; $$index++) {
        let command = each_array[$$index];
        $$renderer2.push(`<button type="button"><span>${escape_html(command.name)}</span> <small>${escape_html(command.description)}</small></button>`);
      }
      $$renderer2.push(`<!--]--></div></div></div>`);
    } else {
      $$renderer2.push("<!--[-1-->");
    }
    $$renderer2.push(`<!--]-->`);
    bind_props($$props, { open, runCommand });
  });
}
function StatusWidget($$renderer, $$props) {
  $$renderer.component(($$renderer2) => {
    let principle;
    const principles = [
      "Simple is not the same as shallow.",
      "Controls should survive tired people.",
      "Compliance should clarify work.",
      "Good systems reduce heroics.",
      "No beige unless unavoidable."
    ];
    let principleIndex = 0;
    onDestroy(() => {
    });
    principle = principles[principleIndex % principles.length];
    $$renderer2.push(`<aside class="widgets" aria-label="ianOS status widgets"><section class="widget"><h2>Current Mission</h2> <p>Building useful infrastructure for people doing difficult work: everwished, charIT, River &amp; Bean, Happy Coo, media, training and the apparently sensible idea that escaped containment this week.</p></section> <section class="widget"><h2>Availability</h2> <p>Available for selected consulting, training, advisory, charity/community digital work and interesting problems with honest constraints.</p></section> <section class="widget"><h2>Principle</h2> <p>${escape_html(principle)}</p></section> <section class="widget"><h2>Build Status</h2> <p>public CV: active<br/>creative subsystem: admitted<br/>beige levels: monitored<br/>mission drift: contained, mostly</p></section></aside>`);
  });
}
function Taskbar($$renderer, $$props) {
  $$renderer.component(($$renderer2) => {
    let windows = fallback($$props["windows"], () => [], true);
    let openApp = $$props["openApp"];
    let restoreApp = $$props["restoreApp"];
    let openPalette = $$props["openPalette"];
    $$renderer2.push(`<nav class="taskbar" aria-label="ianOS taskbar"><button type="button" class="taskbar__start">ianOS</button> <button type="button">Command</button> <a href="/simple">Simple Mode</a> <div class="taskbar__windows" aria-label="Open windows"><!--[-->`);
    const each_array = ensure_array_like(windows);
    for (let $$index = 0, $$length = each_array.length; $$index < $$length; $$index++) {
      let item = each_array[$$index];
      const app = appsById.get(item.id);
      if (app) {
        $$renderer2.push("<!--[0-->");
        $$renderer2.push(`<button type="button"${attr_class("", void 0, { "minimised": item.minimised })}>${escape_html(app.shortTitle)}</button>`);
      } else {
        $$renderer2.push("<!--[-1-->");
      }
      $$renderer2.push(`<!--]-->`);
    }
    $$renderer2.push(`<!--]--></div> <button type="button" class="taskbar__control">Control</button></nav>`);
    bind_props($$props, { windows, openApp, restoreApp, openPalette });
  });
}
function ControlPanel($$renderer, $$props) {
  $$renderer.component(($$renderer2) => {
    var $$store_subs;
    let replayBoot = $$props["replayBoot"];
    $$renderer2.push(`<section class="control-panel" aria-label="Control Panel"><h2>Control Panel</h2> <div class="control-grid"><section><h3>Boot</h3> <p>Replay the verification identity screen and ianOS boot sequence.</p> <button type="button">Replay Boot</button></section> <section><h3>Simple Mode</h3> <label class="switch"><input type="checkbox"${attr("checked", store_get($$store_subs ??= {}, "$preferences", preferences).simpleModePreferred, true)}/> <span>Prefer simple reading mode</span></label> <a href="/simple">Open Simple Mode</a></section> <section><h3>Theme</h3> <div class="segmented" aria-label="Theme selector"><button type="button"${attr_class("", void 0, {
      "active": store_get($$store_subs ??= {}, "$preferences", preferences).theme === "ianos"
    })}>ianOS</button> <button type="button"${attr_class("", void 0, {
      "active": store_get($$store_subs ??= {}, "$preferences", preferences).theme === "verified"
    })}>Verified</button></div></section> <section><h3>Privacy</h3> <p>No analytics, no autoplay audio, no login, no user tracking. The only persistence is local UI preference storage.</p></section></div></section>`);
    if ($$store_subs) unsubscribe_stores($$store_subs);
    bind_props($$props, { replayBoot });
  });
}
function Terminal($$renderer, $$props) {
  $$renderer.component(($$renderer2) => {
    let runCommand = $$props["runCommand"];
    let input = "";
    let lines = [
      { kind: "output", text: "ianOS terminal" },
      {
        kind: "output",
        text: "Type help for commands. Type no-beige for policy."
      }
    ];
    $$renderer2.push(`<div class="terminal-panel"><div class="terminal-output" aria-live="polite"><!--[-->`);
    const each_array = ensure_array_like(lines);
    for (let $$index = 0, $$length = each_array.length; $$index < $$length; $$index++) {
      let line = each_array[$$index];
      $$renderer2.push(`<pre${attr_class("", void 0, { "terminal-input-line": line.kind === "input" })}>${escape_html(line.text)}</pre>`);
    }
    $$renderer2.push(`<!--]--></div> <form class="terminal-form"><label for="terminal-input">></label> <input id="terminal-input"${attr("value", input)} autocomplete="off" spellcheck="false"/> <button type="submit">run</button></form></div>`);
    bind_props($$props, { runCommand });
  });
}
let zCounter = 20;
function defaultPosition(index) {
  return {
    x: 120 + index % 5 * 34,
    y: 86 + index % 5 * 30
  };
}
function createWindowStore() {
  const { subscribe, update } = writable([]);
  function focusWindow(id) {
    update(
      (windows) => windows.map((item) => item.id === id ? { ...item, z: ++zCounter, minimised: false } : item)
    );
  }
  return {
    subscribe,
    openWindow(id) {
      const app = appsById.get(id);
      if (!app) return;
      const existing = get({ subscribe }).find((item) => item.id === id);
      if (existing) {
        focusWindow(id);
        return;
      }
      update((windows) => {
        const position = defaultPosition(windows.length);
        return [
          ...windows,
          {
            id,
            x: position.x,
            y: position.y,
            width: app.defaultSize.width,
            height: app.defaultSize.height,
            z: ++zCounter,
            minimised: false,
            maximised: false
          }
        ];
      });
    },
    closeWindow(id) {
      update((windows) => windows.filter((item) => item.id !== id));
    },
    minimiseWindow(id) {
      update(
        (windows) => windows.map((item) => item.id === id ? { ...item, minimised: true } : item)
      );
    },
    restoreWindow(id) {
      focusWindow(id);
    },
    focusWindow,
    toggleMaximise(id) {
      update(
        (windows) => windows.map(
          (item) => item.id === id ? { ...item, maximised: !item.maximised, minimised: false, z: ++zCounter } : item
        )
      );
    },
    moveWindow(id, x, y) {
      update((windows) => windows.map((item) => item.id === id ? { ...item, x, y } : item));
    },
    resizeWindow(id, width, height) {
      update(
        (windows) => windows.map((item) => item.id === id ? { ...item, width, height } : item)
      );
    }
  };
}
const windowStore = createWindowStore();
function Window($$renderer, $$props) {
  $$renderer.component(($$renderer2) => {
    let app;
    let item = $$props["item"];
    let runCommand = $$props["runCommand"];
    let replayBoot = $$props["replayBoot"];
    app = appsById.get(item.id);
    if (app && !item.minimised) {
      $$renderer2.push("<!--[0-->");
      $$renderer2.push(`<section${attr_class("os-window", void 0, { "maximised": item.maximised })}${attr_style(`--window-x: ${item.x}px; --window-y: ${item.y}px; --window-width: ${item.width}px; --window-height: ${item.height}px; z-index: ${item.z};`)}${attr("aria-label", app.title)}><header class="os-window__titlebar" role="toolbar"${attr("aria-label", `${app.shortTitle} window controls`)} tabindex="0"><span class="os-window__icon" aria-hidden="true">${escape_html(app.icon)}</span> <h2>${escape_html(app.title)}</h2> <div class="os-window__actions"><button type="button"${attr("aria-label", `Minimise ${app.shortTitle}`)}>-</button> <button type="button"${attr("aria-label", `Maximise ${app.shortTitle}`)}>${escape_html(item.maximised ? "<>" : "[]")}</button> <button type="button"${attr("aria-label", `Close ${app.shortTitle}`)}>x</button></div></header> <div class="os-window__body">`);
      if (app.id === "terminal") {
        $$renderer2.push("<!--[0-->");
        Terminal($$renderer2, { runCommand });
      } else if (app.id === "control") {
        $$renderer2.push("<!--[1-->");
        ControlPanel($$renderer2, { replayBoot });
      } else {
        $$renderer2.push("<!--[-1-->");
        ContentWindow($$renderer2, { app });
      }
      $$renderer2.push(`<!--]--></div> <button type="button" class="os-window__resize"${attr("aria-label", `Resize ${app.shortTitle}`)}></button></section>`);
    } else {
      $$renderer2.push("<!--[-1-->");
    }
    $$renderer2.push(`<!--]-->`);
    bind_props($$props, { item, runCommand, replayBoot });
  });
}
function Desktop($$renderer, $$props) {
  $$renderer.component(($$renderer2) => {
    var $$store_subs;
    let bootVisible = true;
    let paletteOpen = false;
    let currentTime = "";
    const desktopApps = visibleApps;
    function openApp(id) {
      windowStore.openWindow(id);
    }
    function restoreApp(id) {
      windowStore.restoreWindow(id);
    }
    function replayBoot() {
      preferences.resetBoot();
      bootVisible = true;
    }
    function runCommand(commandInput, source = "palette") {
      const command = findCommand(commandInput);
      if (!command) {
        return `Command not found: ${commandInput}
Type help for available commands.`;
      }
      if (command.name === "help") return helpText;
      if (command.appId) {
        openApp(command.appId);
        return `[open] ${command.appId}`;
      }
      if (command.name === "simple") {
        return "Opening Simple Mode.";
      }
      if (command.name === "boot") {
        replayBoot();
        return "Replaying boot sequence.";
      }
      if (command.name === "verify") {
        openApp("evidence");
        return "Verification route opened. Trust comes from what can be checked.";
      }
      if (command.name === "responsibility") {
        openApp("everwished");
        return "Responsibility by Design: care about consequences before the invoice has cooled.";
      }
      if (command.name === "no-beige") {
        return [
          "NO BEIGE DECLARATION",
          "",
          "This system rejects:",
          "- unnecessary jargon",
          "- dead-eyed compliance theatre",
          "- vendor fog",
          "- fake transformation",
          "- fragile spreadsheets with delusions of platformhood",
          '- "just circle back" as a substitute for action',
          "",
          "Proceed with useful work."
        ].join("\n");
      }
      if (command.name === "gyp") {
        return "GypBops subsystem detected.\nStatus: hypnotic\nRisk level: squeaky\nBusiness justification: none, which is sometimes the purest kind.";
      }
      if (command.name === "duck") {
        return "Duck mode enabled.\nNo strategic value detected.\nMorale impact: suspiciously high.";
      }
      if (source === "palette") return `${command.name} acknowledged.`;
      return void 0;
    }
    let $$settled = true;
    let $$inner_renderer;
    function $$render_inner($$renderer3) {
      head("o7vsfr", $$renderer3, ($$renderer4) => {
        $$renderer4.title(($$renderer5) => {
          $$renderer5.push(`<title>Ian Barrs - IT, Security, Operations, Training and Useful Systems</title>`);
        });
        $$renderer4.push(`<meta name="description" content="Ian Barrs is an IT, security, compliance, operations and training specialist, founder of everwished ltd, and builder of practical systems for small organisations, charities, community projects and people doing difficult work."/> <meta property="og:title" content="Ian Barrs - useful systems, useful mischief"/> <meta property="og:description" content="Useful systems, useful mischief. The interactive public CV of Ian Barrs: IT, security, compliance, operations, training, everwished, charIT, River &amp; Bean, Happy Coo and more."/>`);
      });
      $$renderer3.push(`<main class="desktop-shell" aria-label="ianOS desktop">`);
      if (bootVisible) {
        $$renderer3.push("<!--[0-->");
        BootScreen($$renderer3);
      } else {
        $$renderer3.push("<!--[-1-->");
      }
      $$renderer3.push(`<!--]--> <div class="desktop-topbar" aria-label="System status"><span>ianOS</span> <span>${escape_html(currentTime)}</span> <button type="button">Ctrl+K</button></div> <section class="desktop" aria-label="Desktop apps"><div class="desktop-icons"><!--[-->`);
      const each_array = ensure_array_like(desktopApps);
      for (let $$index = 0, $$length = each_array.length; $$index < $$length; $$index++) {
        let app = each_array[$$index];
        AppIcon($$renderer3, { app, openApp });
      }
      $$renderer3.push(`<!--]--></div> `);
      StatusWidget($$renderer3);
      $$renderer3.push(`<!----> <!--[-->`);
      const each_array_1 = ensure_array_like(store_get($$store_subs ??= {}, "$windowStore", windowStore));
      for (let $$index_1 = 0, $$length = each_array_1.length; $$index_1 < $$length; $$index_1++) {
        let item = each_array_1[$$index_1];
        Window($$renderer3, { item, runCommand, replayBoot });
      }
      $$renderer3.push(`<!--]--></section> `);
      Taskbar($$renderer3, {
        windows: store_get($$store_subs ??= {}, "$windowStore", windowStore),
        openApp,
        restoreApp,
        openPalette: () => paletteOpen = true
      });
      $$renderer3.push(`<!----> `);
      CommandPalette($$renderer3, {
        runCommand,
        get open() {
          return paletteOpen;
        },
        set open($$value) {
          paletteOpen = $$value;
          $$settled = false;
        }
      });
      $$renderer3.push(`<!----></main>`);
    }
    do {
      $$settled = true;
      $$inner_renderer = $$renderer2.copy();
      $$render_inner($$inner_renderer);
    } while (!$$settled);
    $$renderer2.subsume($$inner_renderer);
    if ($$store_subs) unsubscribe_stores($$store_subs);
  });
}
function _page($$renderer) {
  Desktop($$renderer);
}
export {
  _page as default
};
