"use client";

import { useMemo, useState } from "react";

type Realm = {
  id: string;
  name: string;
  type: string;
  description: string;
  color: string;
  emblem: string;
  x: string;
  y: string;
  size: "sm" | "md" | "lg";
  activity: string;
};

const realms: Realm[] = [
  { id: "kinship", name: "Kinship Duna", type: "Organization", description: "Your founding home", color: "var(--realm-org)", emblem: "/assets/organization-crests/beacon.png", x: "16%", y: "20%", size: "lg", activity: "12 here now" },
  { id: "alliance", name: "Common Ground", type: "Alliance", description: "A shared field of practice", color: "var(--realm-alliance)", emblem: "/assets/realm-emblems/alliance.png", x: "61%", y: "18%", size: "md", activity: "4 Allies gathering" },
  { id: "project", name: "Route Plan", type: "Project", description: "The work taking shape", color: "var(--realm-project)", emblem: "/assets/realm-emblems/project.png", x: "52%", y: "61%", size: "md", activity: "3 actions ready" },
  { id: "relationship", name: "Shared History", type: "Relationship", description: "A living thread", color: "var(--realm-relationship)", emblem: "/assets/realm-emblems/relationship.png", x: "78%", y: "68%", size: "sm", activity: "Engaged" },
  { id: "program", name: "Sunday Studio", type: "Program", description: "A recurring rhythm", color: "var(--realm-program)", emblem: "/assets/realm-emblems/program.png", x: "28%", y: "70%", size: "sm", activity: "Next in 2 days" },
];

const taxonomy = [
  ["Organization", "Radial institution", "var(--realm-org)", "/assets/realm-emblems/organization.png"],
  ["Alliance", "Interlocking centers", "var(--realm-alliance)", "/assets/realm-emblems/alliance.png"],
  ["Program", "Recurring rhythm", "var(--realm-program)", "/assets/realm-emblems/program.png"],
  ["Project", "Finite ascent", "var(--realm-project)", "/assets/realm-emblems/project.png"],
  ["Relationship", "Braided continuity", "var(--realm-relationship)", "/assets/realm-emblems/relationship.png"],
  ["Community", "Gathered difference", "var(--realm-community)", "/assets/realm-emblems/community.png"],
  ["Conceptual", "Unresolved possibility", "var(--realm-conceptual)", "/assets/realm-emblems/conceptual.png"],
] as const;

const organizationCrests = [
  ["Beacon", "Guidance", "/assets/organization-crests/beacon.png"],
  ["Grove", "Cultivation", "/assets/organization-crests/grove.png"],
  ["Bridge", "Passage", "/assets/organization-crests/bridge.png"],
  ["Loom", "Coordination", "/assets/organization-crests/loom.png"],
  ["Summit", "Purpose", "/assets/organization-crests/summit.png"],
  ["Archive", "Continuity", "/assets/organization-crests/archive.png"],
] as const;

const talismans = [
  ["Compass", "Orientation · find the way", "/assets/talismans/compass.png"],
  ["Moon", "Reflection · hold possibility", "/assets/talismans/moon.png"],
  ["Sprout", "Cultivation · help life emerge", "/assets/talismans/sprout.png"],
  ["Tide", "Flow · move with a living rhythm", "/assets/talismans/tide.png"],
  ["Summit", "Purpose · move toward a horizon", "/assets/talismans/summit.png"],
  ["Vessel", "Stewardship · hold shared value", "/assets/talismans/vessel.png"],
] as const;

const geometryParts = [
  ["orbit", "Orbit arc", "belonging · context · gravity"],
  ["journey", "Journey path", "movement · sequence · passage"],
  ["anchor", "Anchor stud", "attachment · commitment · endpoint"],
  ["constellation", "Constellation", "distributed affinity · peers"],
  ["crossing", "Crossing glint", "exchange · encounter · transfer"],
  ["horizon", "Horizon ring", "approach · threshold · nesting"],
] as const;

const elementTypes = [
  ["Actor", "Agentic presence", "var(--element-actor)", "agent"],
  ["Media", "Made and remembered", "var(--element-media)", "discover"],
  ["Ally", "A Source, present", "var(--element-ally)", "ally"],
  ["Resource", "Value in motion", "var(--element-resource)", "treasury"],
  ["Action", "Something to do", "var(--element-action)", "enact"],
] as const;

const stateGrammar = [
  { name: "Open", motion: "Breathe", sigil: "○", copy: "A Realm at rest remains available. 6–8s, scale ≤ 1.035.", className: "open" },
  { name: "Engaged", motion: "Relate", sigil: "∴", copy: "Relevant nodes connect; paths brighten only while relationship is active.", className: "engaged" },
  { name: "Focused", motion: "Gather", sigil: "✦", copy: "Elements settle toward a task. Arrival takes 900ms, never a pop.", className: "focused" },
  { name: "Dreaming", motion: "Drift", sigil: "☾", copy: "Possibility wanders gently. ±8px over 14–18s, with no viewport motion.", className: "dreaming" },
];

const allyMoods = [
  ["open", "Available · welcoming · present"],
  ["engaged", "Conversing · collaborating · responding"],
  ["focused", "Working · reviewing · making"],
  ["dreaming", "Imagining · reflecting · exploring"],
] as const;

const allyPersonas = ["01", "02", "03", "04", "05", "06"] as const;

function Icon({ name }: { name: string }) {
  if (name === "ally") {
    return <img className="icon ally-icon" src="/assets/allies/ally-open-sample.png" alt="" />;
  }
  return <img className="icon" src={`/assets/icons/${name}.svg`} alt="" />;
}

function RealmNode({ realm, selected, onSelect }: { realm: Realm; selected: boolean; onSelect: () => void }) {
  return (
    <button
      className={`realm-node realm-node--${realm.size}${selected ? " is-selected" : ""}`}
      style={{ left: realm.x, top: realm.y, "--realm": realm.color } as React.CSSProperties}
      onClick={onSelect}
      aria-label={`Inspect ${realm.name}, ${realm.type}`}
    >
      <span className="realm-node__halo" />
      <span className="realm-node__rim"><img className="realm-emblem" src={realm.emblem} alt="" /></span>
      <span className="realm-label">
        <span className="realm-label__type">{realm.type}</span>
        <strong>{realm.name}</strong>
        <small>{realm.activity}</small>
      </span>
    </button>
  );
}

export default function StudioSystem() {
  const [motion, setMotion] = useState(true);
  const [zoom, setZoom] = useState(1);
  const [selectedId, setSelectedId] = useState("kinship");
  const [entryMode, setEntryMode] = useState<"click" | "approach">("click");
  const [proximity, setProximity] = useState(42);
  const [disclosure, setDisclosure] = useState<"far" | "mid" | "near">("near");
  const selected = useMemo(() => realms.find((realm) => realm.id === selectedId) ?? realms[0], [selectedId]);
  const threshold = proximity >= 78;

  return (
    <main className={motion ? "motion-on" : "motion-off"}>
      <header className="site-header">
        <a className="brand" href="#top" aria-label="Kiduna Studio design system home">
          <img src="/assets/kiduna-mark.svg" alt="" />
          <span><strong>Kiduna</strong><small>Studio system · 0.4</small></span>
        </a>
        <nav aria-label="Studio system sections">
          <a href="#field">Field</a><a href="#realms">Realms</a><a href="#taxonomy">Emblems</a><a href="#talismans">Talismans</a><a href="#organizations">Organizations</a><a href="#allies">Allies</a>
        </nav>
        <a className="download-link" href="#handoff">Implementation brief <span>↓</span></a>
      </header>

      <section className="hero" id="top">
        <div className="hero-copy">
          <p className="eyebrow">Studio · living system proposal</p>
          <h1>Every object carries a <em>celestial signature.</em></h1>
          <p className="hero-lede">The Field is not a dark backdrop with colored dots. It is a living system of brushed-metal frameworks, enamel crests, orbital identities, and connections drawn by gravity.</p>
          <div className="hero-actions">
            <a className="primary-button" href="#field">Enter the Field →</a>
            <button className="motion-toggle" onClick={() => setMotion((value) => !value)} aria-pressed={motion}>
              <span className="toggle-dot" /> Ambient motion {motion ? "on" : "off"}
            </button>
          </div>
          <dl className="hero-principles">
            <div><dt>Ground</dt><dd>Celestial depth, sparse living light</dd></div>
            <div><dt>Objects</dt><dd>Related structures, singular crests</dd></div>
            <div><dt>Connections</dt><dd>Orbital, braided, anchored, alive</dd></div>
          </dl>
        </div>

        <div className="hero-field" aria-label="Interactive Studio Field example">
          <div className="field-chrome"><span>Return · Sunday 6:42 PM</span><strong>The Field is alive</strong></div>
          <div className="compute-pill"><span>✦</span><strong>2,240</strong><small>$KIDUNA</small></div>
          <div className="field-world" style={{ transform: `scale(${zoom})` }}>
            <i className="orbit-arc arc-1" /><i className="orbit-arc arc-2" /><i className="orbit-arc arc-3" />
            <i className="field-glint glint-1" /><i className="field-glint glint-2" /><i className="field-glint glint-3" /><i className="field-glint glint-4" />
            <div className="relation-thread thread-a" /><div className="relation-thread thread-b" />
            {realms.map((realm) => <RealmNode key={realm.id} realm={realm} selected={selectedId === realm.id} onSelect={() => setSelectedId(realm.id)} />)}
            <button className="ally-presence" aria-label="Your Ally, Open"><img src="/assets/allies/ally-open-sample.png" alt="Your Ally" /><span>You · open</span></button>
          </div>
          <div className="field-controls" aria-label="Field zoom controls">
            <button onClick={() => setZoom((v) => Math.max(.84, +(v - .08).toFixed(2)))} aria-label="Zoom out">−</button>
            <span>{Math.round(zoom * 100)}%</span>
            <button onClick={() => setZoom((v) => Math.min(1.24, +(v + .08).toFixed(2)))} aria-label="Zoom in">+</button>
          </div>
          <aside className="realm-peek">
            <span style={{ color: selected.color }}>{selected.type}</span>
            <strong>{selected.name}</strong>
            <p>{selected.description}</p>
          </aside>
        </div>
      </section>

      <section className="system-section field-section" id="field">
        <div className="section-heading">
          <p className="eyebrow">01 · Field ground & ambient motion</p>
          <h2>A dark field should feel <em>deep, not empty.</em></h2>
          <p>The ground stays crisp at near-black umber. Warmth belongs to objects: reflected enamel light, thin orbit engravings, and sparse cream or gold glints.</p>
        </div>
        <div className="ground-specimen">
          <div className="ground-layer"><i className="orbit-arc arc-1" /><i className="orbit-arc arc-2" /><i className="field-glint glint-1" /><i className="field-glint glint-3" /></div>
          <div className="specimen-copy"><span>FIELD GROUND</span><strong>#0A0604</strong><p>No grid. No wash. Camel arcs at ≤ 10% opacity. Light gathers locally around meaning.</p></div>
          <div className="material-chips"><span>Lacquer</span><span>Enamel</span><span>Gold wire</span><span>Moon cream</span></div>
        </div>
        <div className="state-grid">
          {stateGrammar.map((state) => (
            <article className={`state-card state-card--${state.className}`} key={state.name}>
              <div className="state-orb"><span>{state.sigil}</span></div>
              <p className="eyebrow">{state.name} field</p>
              <h3>{state.motion}</h3>
              <p>{state.copy}</p>
            </article>
          ))}
        </div>
        <div className="connection-system">
          <div className="connection-copy"><p className="eyebrow">Connection grammar</p><h3>Relationships have shape.</h3><p>Lines are never decorative. Every curve reveals membership, exchange, attention, passage, or shared gravity.</p></div>
          <div className="connection-pattern pattern-orbit"><i /><i /><b /><span>Orbit</span><small>belonging</small></div>
          <div className="connection-pattern pattern-braid"><i /><i /><b /><span>Braid</span><small>reciprocity</small></div>
          <div className="connection-pattern pattern-anchor"><i /><i /><b /><span>Anchor</span><small>commitment</small></div>
          <div className="connection-pattern pattern-crossing"><i /><i /><b /><span>Crossing</span><small>exchange</small></div>
        </div>
        <div className="rule-band">
          <div><strong>Pan</strong><span>Direct 1:1 movement; the Field moves, chrome never does.</span></div>
          <div><strong>Zoom</strong><span>Cursor-centered, continuous, 0.7×–2.4×; labels resolve by distance.</span></div>
          <div><strong>Gather</strong><span>900ms settle, 120–150ms stagger. Nothing pops into existence.</span></div>
          <div><strong>Reduce</strong><span>Preserve depth and state; stop drift, orbit, pulse, and parallax.</span></div>
        </div>
      </section>

      <section className="system-section realms-section" id="realms">
        <div className="section-heading split-heading">
          <div><p className="eyebrow">02 · Realms</p><h2>Every Realm is a <em>vessel.</em></h2></div>
          <p>Realm medallions borrow the crafted depth of Allies without becoming portraits. A click opens knowledge. An approach crosses into context.</p>
        </div>
        <div className="entry-demo">
          <div className="entry-tabs" role="tablist" aria-label="Realm entry mode">
            <button className={entryMode === "click" ? "active" : ""} onClick={() => setEntryMode("click")} role="tab" aria-selected={entryMode === "click"}>Click → Panel</button>
            <button className={entryMode === "approach" ? "active" : ""} onClick={() => setEntryMode("approach")} role="tab" aria-selected={entryMode === "approach"}>Approach → Threshold</button>
          </div>
          <div className={`entry-stage entry-stage--${entryMode}${threshold ? " is-threshold" : ""}`}>
            <div className="entry-field"><i className="orbit-arc arc-1" /><i className="orbit-arc arc-2" />
              <button className="realm-vessel" onClick={() => setEntryMode("click")} aria-label="Open Kinship Duna Realm panel">
                <span className="threshold-ring" /><span className="vessel-rim"><img src="/assets/organization-crests/beacon.png" alt="" /></span>
                <span className="vessel-label"><small>Organization</small><strong>Kinship Duna</strong><span>Your founding home</span></span>
                <span className="nested n1"><Icon name="alliance" /></span><span className="nested n2"><Icon name="build" /></span><span className="nested n3"><Icon name="kinship" /></span>
              </button>
            </div>
            {entryMode === "click" ? (
              <aside className="realm-panel"><p className="eyebrow">Organization</p><h3>Kinship Duna</h3><p>A living vessel for twelve Allies, three active Projects, and the relationships between them.</p><div className="panel-stat"><strong>12</strong><span>Allies here now</span></div><button>Enter Organization →</button><small>Click informs before it transports.</small></aside>
            ) : (
              <aside className="approach-control"><p className="eyebrow">Approach</p><h3>{threshold ? "Threshold ready" : "The Realm draws nearer"}</h3><p>{threshold ? "Release or continue to cross into Kinship Duna." : "Scale, label detail, and reflected light increase with proximity."}</p><input aria-label="Distance to Realm" type="range" min="0" max="100" value={proximity} onChange={(event) => setProximity(Number(event.target.value))} /><div><span>Field</span><strong>{proximity}%</strong><span>Inside</span></div></aside>
            )}
          </div>
        </div>

        <div className="transition-steps">
          <article><span>01</span><strong>Recognize</strong><p>Rim, icon, label, and nested glints establish the vessel at distance.</p></article>
          <article><span>02</span><strong>Approach</strong><p>The rim becomes a horizon. The Realm hue reflects locally into the ground.</p></article>
          <article><span>03</span><strong>Cross</strong><p>The vessel fills the view; contents gather with a warm staggered settle.</p></article>
          <article><span>04</span><strong>Work within</strong><p>The interior is another Field. Parent context remains as the path back.</p></article>
        </div>
      </section>

      <section className="system-section taxonomy-section" id="taxonomy">
        <div className="section-heading">
          <p className="eyebrow">03 · Field taxonomy & Realm anatomy</p>
          <h2>Geometry identifies. Enamel <em>makes it belong.</em></h2>
          <p>Realm identity begins with crest geometry, then gains enamel color, metal depth, constellation nodes, and a stable orbital signature.</p>
        </div>
        <div className="taxonomy-grid">
          {taxonomy.map(([name, note, color, emblem]) => (
            <article className={`taxonomy-card${name === "Conceptual" ? " conceptual" : ""}`} style={{ "--realm": color } as React.CSSProperties} key={name}>
              <div className="taxonomy-orb"><img src={emblem} alt={`${name} Realm emblem`} /></div><strong>{name}</strong><small>{note}</small>
            </article>
          ))}
        </div>

        <div className="anatomy-row">
          <div className="anatomy-visual">
            <div className="anatomy-realm"><span className="anatomy-halo" /><span className="anatomy-rim"><img src="/assets/realm-emblems/organization.png" alt="Organization emblem anatomy" /></span></div>
            <div className="anatomy-label"><small>Organization</small><strong>Kinship Duna</strong><p>Your founding home</p><span><i />12 here now · 3 projects</span></div>
            <i className="callout-line line-rim"><b>01</b><span>Enamel rim + reflected light</span></i>
            <i className="callout-line line-core"><b>02</b><span>Dark core + type icon</span></i>
            <i className="callout-line line-label"><b>03</b><span>Attached label, never floating</span></i>
          </div>
          <div className="disclosure-demo">
            <p className="eyebrow">Progressive disclosure</p>
            <div className="segmented" role="group" aria-label="Disclosure distance">
              {(["far", "mid", "near"] as const).map((value) => <button key={value} className={disclosure === value ? "active" : ""} onClick={() => setDisclosure(value)}>{value}</button>)}
            </div>
            <div className={`disclosure-specimen disclosure-${disclosure}`}><span className="mini-vessel"><Icon name="kinship" /></span><div><small>Relationship</small><strong>Shared History</strong><p>A living thread · here now</p></div></div>
            <p className="disclosure-rule">{disclosure === "far" ? "Far: a warm glint and type hue establish existence." : disclosure === "mid" ? "Mid: icon and Goudy name establish identity." : "Near: type, name, description, activity, and nested contents resolve."}</p>
          </div>
        </div>

        <div className="element-section"><p className="eyebrow">Elements inside a Realm</p><div className="element-grid">
          {elementTypes.map(([name, note, color, icon]) => <article style={{ "--element": color } as React.CSSProperties} key={name}><div><Icon name={icon} /></div><span><strong>{name}</strong><small>{note}</small></span></article>)}
        </div></div>
      </section>

      <section className="system-section talisman-section" id="talismans">
        <div className="section-heading split-heading"><div><p className="eyebrow">04 · Talismans & celestial geometry</p><h2>A vocabulary designed to be <em>recomposed.</em></h2></div><p>Talismans are portable symbols of meaning, not Realm types and not identities. The geometry around them is a kit of semantic parts: each arc, node, stud, path, and glint earns its place.</p></div>

        <div className="talisman-grid">
          {talismans.map(([name, meaning, image]) => <article key={name}><div><img src={image} alt={`${name} talisman`} /></div><strong>{name}</strong><small>{meaning}</small></article>)}
        </div>

        <div className="composition-lab">
          <div className="celestial-composition" aria-label="Recomposed talisman and connector example">
            <i className="geo-orbit geo-orbit--outer" /><i className="geo-orbit geo-orbit--inner" /><i className="geo-path geo-path--a" /><i className="geo-path geo-path--b" />
            <i className="geo-glint g1" /><i className="geo-glint g2" /><i className="geo-glint g3" /><i className="geo-anchor a1" /><i className="geo-anchor a2" />
            <img className="lab-talisman lab-talisman--main" src="/assets/talismans/compass.png" alt="Compass talisman" />
            <img className="lab-talisman lab-talisman--one" src="/assets/talismans/sprout.png" alt="Sprout talisman" />
            <img className="lab-talisman lab-talisman--two" src="/assets/talismans/moon.png" alt="Moon talisman" />
          </div>
          <div className="composition-layers"><p className="eyebrow">Composition order</p><h3>Ground → geometry → connection → object → signal</h3><ol><li><b>Ground</b><span>Deep umber lacquer; no decorative wash.</span></li><li><b>Geometry</b><span>Quiet orbital scaffolding establishes gravity.</span></li><li><b>Connection</b><span>Semantic paths join anchored points.</span></li><li><b>Object</b><span>Ally, Realm, Element, or Talisman occupies the field.</span></li><li><b>Signal</b><span>One active glint or enamel pulse reveals change.</span></li></ol></div>
        </div>

        <div className="geometry-kit">
          {geometryParts.map(([kind, name, meaning]) => <article key={kind}><div className={`geometry-swatch geometry-swatch--${kind}`}><i /><i /><b /><span /></div><strong>{name}</strong><small>{meaning}</small></article>)}
        </div>

        <div className="connector-matrix">
          <div><span>Form</span><span>Meaning</span><span>Construction</span><span>Active signal</span></div>
          <div><strong>Orbit</strong><span>Belonging</span><span>Elliptical, object-centered</span><span>One phase node brightens</span></div>
          <div><strong>Tether</strong><span>Direct relation</span><span>One curved path, stud to stud</span><span>Light travels once</span></div>
          <div><strong>Braid</strong><span>Reciprocity</span><span>Two paths exchange position</span><span>Shared crossing glows</span></div>
          <div><strong>Confluence</strong><span>Gathering</span><span>Two or more paths become one</span><span>Merge point breathes</span></div>
          <div><strong>Threshold</strong><span>Entry</span><span>Arc expands toward horizon</span><span>Rim becomes moon-cream</span></div>
        </div>
      </section>

      <section className="system-section organization-section" id="organizations">
        <div className="section-heading split-heading"><div><p className="eyebrow">05 · Organization signatures</p><h2>One structure. <em>Many identities.</em></h2></div><p>Organizations form a recognizable family before the viewer reads a label. Their identity comes from controlled variation—not an arbitrary logo pasted inside the same circle.</p></div>
        <div className="organization-grid">
          {organizationCrests.map(([name, meaning, image]) => <article key={name}><img src={image} alt={`${name} Organization crest`} /><div><strong>{name}</strong><small>{meaning}</small></div></article>)}
        </div>
        <div className="variation-axis">
          <div><span>Fixed</span><strong>Family silhouette</strong><p>Double metal rim, four cardinal studs, dark enamel core, radial scaffold.</p></div>
          <div><span>Variable</span><strong>Central crest</strong><p>One simple geometry expressing the Organization’s chosen character.</p></div>
          <div><span>Variable</span><strong>Enamel pair</strong><p>Two approved colors, one dominant and one relational accent.</p></div>
          <div><span>Variable</span><strong>Star signature</strong><p>Three to six deterministic nodes generated from the Organization ID.</p></div>
          <div><span>Variable</span><strong>Engraving</strong><p>One orbit rhythm or lattice pattern, stable across every appearance.</p></div>
        </div>
      </section>

      <section className="system-section allies-section" id="allies">
        <div className="section-heading split-heading"><div><p className="eyebrow">06 · Allies · six Personas, four moods</p><h2>Identity stays. <em>Context changes.</em></h2></div><p>All 24 examples show the same six Personas across Open, Engaged, Focused, and Dreaming. Face, age, hair, adornment, and silhouette remain stable; gaze, pose, cheek sigil, and celestial field express the current mood.</p></div>
        <div className="ally-gallery">
          {allyPersonas.map((persona) => <article className="persona-set" key={persona}>
            <header><span>Persona {persona}</span><strong>One Ally · four contextual moods</strong></header>
            <div className="persona-moods">
              {allyMoods.map(([mood, description]) => <figure key={mood}>
                <div><img src={`/assets/allies/personas/persona-${persona}-${mood}.jpg`} alt={`Persona ${persona}, ${mood} mood`} /></div>
                <figcaption><strong>{mood.toUpperCase()}</strong><small>{description}</small></figcaption>
              </figure>)}
            </div>
          </article>)}
        </div>
        <div className="ally-contract"><div><span>Source</span><strong>The actual person</strong><p>Owns identity, permissions, and representation.</p></div><i>→</i><div><span>Ally</span><strong>The Source inside Kiduna</strong><p>Persistent across every Studio depth and state.</p></div><i>→</i><div><span>State</span><strong>Context, not identity</strong><p>Changes gaze, sigil, field, and motion—never the person.</p></div></div>
      </section>

      <section className="handoff-section" id="handoff">
        <p className="eyebrow">Implementation handoff</p>
        <h2>One system. <em>Ready to build.</em></h2>
        <p>The implementation kit contains the complete Studio enamel canon, motion and interaction rules, token sheet, revised reference cards, Ally system, assets, and this site’s source.</p>
        <a className="primary-button" href="#top">Return to the Field →</a>
      </section>

      <footer><img src="/assets/kiduna-mark.svg" alt="Kiduna" /><p>Exceptional People and Intelligent Agents working together as one.</p><span>Studio system · 22 July 2026</span></footer>
    </main>
  );
}
