import { useMemo, useState, type CSSProperties } from "react";
import HexLattice, { type HexNode } from "./HexLattice";

export type RingIndex = 0 | 1 | 2 | 3 | 4 | 5 | 6;

interface RingMeta {
  ring: RingIndex;
  name: string;
  size: number;
  tempo: string;
  root: string;
  assignment: string;
  sees: string;
  summary: string;
  color: string;
}

export interface RingGravityMapProps {
  title?: string;
  subtitle?: string;
  initialRing?: RingIndex;
  occupancy?: Partial<Record<RingIndex, number>>;
  onRingChange?: (ring: RingMeta) => void;
}

const RINGS: RingMeta[] = [
  {
    ring: 0,
    name: "YOU",
    size: 1,
    tempo: "Fixed",
    root: "—",
    assignment: "Identity center",
    sees: "Yourself",
    summary: "The center hex is fixed. Everything grows outward from here.",
    color: "#d4a574",
  },
  {
    ring: 1,
    name: "Inner Circle",
    size: 6,
    tempo: "Yearly",
    root: "6",
    assignment: "Manual claim · bidirectional",
    sees: "Full cart resonance",
    summary: "Claimed once, held nearly permanently, and only released by mutual agreement.",
    color: "#e8c4a0",
  },
  {
    ring: 2,
    name: "Archetypes",
    size: 12,
    tempo: "Quarterly",
    root: "3",
    assignment: "Manual curation",
    sees: "Category-level resonance",
    summary: "Roles, not people. One person can fill several slots at once.",
    color: "#a8d4a8",
  },
  {
    ring: 3,
    name: "The Longing",
    size: 18,
    tempo: "Monthly",
    root: "9",
    assignment: "Auto-fill from circulation",
    sees: "Monthly longing patterns",
    summary: "What you are reaching for in this chapter of your life.",
    color: "#7eb8c9",
  },
  {
    ring: 4,
    name: "The Echo",
    size: 24,
    tempo: "Weekly",
    root: "6",
    assignment: "Auto from creative output",
    sees: "Cart + creative output",
    summary: "People who reflect your creative signal back to you.",
    color: "#c9a8d4",
  },
  {
    ring: 5,
    name: "The Wave",
    size: 30,
    tempo: "Daily",
    root: "3",
    assignment: "Auto from Echo convergence",
    sees: "Sustained complementarity",
    summary: "Daily confirmation that motion is building in the same direction.",
    color: "#d4a8b4",
  },
  {
    ring: 6,
    name: "The Current",
    size: 36,
    tempo: "Hourly",
    root: "9",
    assignment: "Auto from Wave alignment",
    sees: "Ambient warmth only",
    summary: "The living surface. Ephemeral people, fresh every hour.",
    color: "#8a9ba8",
  },
];

const DEFAULT_OCCUPANCY: Record<RingIndex, number> = {
  0: 1,
  1: 4,
  2: 5,
  3: 7,
  4: 9,
  5: 12,
  6: 16,
};

const RING_MECHANICS: Record<RingIndex, { trigger: string; persistence: string; governance: string }> = {
  0: {
    trigger: "Identity is established once and held in place.",
    persistence: "Fixed center",
    governance: "Cannot be moved or taken",
  },
  1: {
    trigger: "Manual claim from both sides.",
    persistence: "Yearly cadence",
    governance: "Bidirectional, nearly permanent",
  },
  2: {
    trigger: "Manual curation of roles and archetypes.",
    persistence: "Quarterly review",
    governance: "One person may fill multiple slots",
  },
  3: {
    trigger: "Auto-fill from circulation when longing rises.",
    persistence: "Monthly cadence",
    governance: "Living list, seasonally updated",
  },
  4: {
    trigger: "Auto from creative output and reflection.",
    persistence: "Weekly cadence",
    governance: "Emerges from what you make",
  },
  5: {
    trigger: "Auto from Echo convergence.",
    persistence: "Daily cadence",
    governance: "Sustained motion, not a spike",
  },
  6: {
    trigger: "Auto from Wave alignment.",
    persistence: "Hourly refresh",
    governance: "Ambient atmosphere, ephemeral",
  },
};

function clamp(value: number, min: number, max: number) {
  return Math.max(min, Math.min(max, value));
}

function ringFill(selected: number, total: number) {
  return Math.round(clamp((selected / total) * 100, 0, 100));
}

function ringFillWidth(selected: number, total: number) {
  return `${ringFill(selected, total)}%`;
}

function buildPreviewNodes(ring: RingIndex, occupied: number): HexNode[] {
  const nodes: HexNode[] = [
    {
      id: "ring-center",
      ring: 0,
      position: 0,
      label: "YOU",
      type: "you",
    },
  ];

  if (ring === 0) return nodes;

  const ringMeta = RINGS[ring];
  const count = clamp(occupied, 0, ringMeta.size);

  for (let position = 0; position < ringMeta.size; position += 1) {
    const occupiedSlot = position < count;
    const isDimSlot = ring === 1 && !occupiedSlot;

    nodes.push({
      id: `ring-${ring}-${position}`,
      ring,
      position,
      label: occupiedSlot ? (ring === 6 ? undefined : `${ring}.${position + 1}`) : isDimSlot ? `Dim ${position + 1}` : undefined,
      type: occupiedSlot
        ? ring === 6
          ? position % 3 === 0
            ? "resonance-hot"
            : position % 3 === 1
              ? "resonance-warm"
              : "resonance-cool"
          : "person"
        : isDimSlot
          ? "dim"
          : "empty",
      resonanceSignal: occupiedSlot && ring === 6 ? (position % 3 === 0 ? "hearts" : position % 3 === 1 ? "stars" : "moons") : undefined,
    });
  }

  return nodes;
}

function toneForRing(ring: RingIndex) {
  return RINGS[ring].color;
}

function directionLabel(ring: RingIndex) {
  if (ring === 0) return "identity";
  if (ring === 1) return "mutual claim";
  if (ring === 2) return "role curation";
  if (ring === 3) return "longing";
  if (ring === 4) return "creative echo";
  if (ring === 5) return "daily wave";
  return "ambient current";
}

export default function RingGravityMap({
  title = "Ring Gravity Map",
  subtitle = "A tempo-aware ring map for Cascade — fixed center, mutual claims, and hourly atmosphere.",
  initialRing = 6,
  occupancy,
  onRingChange,
}: RingGravityMapProps) {
  const [selectedRing, setSelectedRing] = useState<RingIndex>(initialRing);

  const counts = useMemo(() => ({ ...DEFAULT_OCCUPANCY, ...occupancy }), [occupancy]);
  const ringKey = selectedRing as RingIndex;
  const selected = RINGS[ringKey];
  const selectedCount = counts[ringKey] ?? DEFAULT_OCCUPANCY[ringKey];
  const selectedFill = ringFill(selectedCount, selected.size);
  const previewNodes = useMemo(() => buildPreviewNodes(ringKey, selectedCount), [selectedCount, ringKey]);

  const filledCapacity = RINGS.reduce((sum, ring) => sum + (counts[ring.ring] ?? DEFAULT_OCCUPANCY[ring.ring]), 0) - 1;
  const totalCapacity = 126;
  const dimmedSlots = Math.max(selected.size - selectedCount, 0);
  const dimmedLabel = selectedRing === 1 ? "Dim hexes" : "Empty slots";
  const mechanics = RING_MECHANICS[ringKey];
  const activeTempo = selected.ring === 6 ? "Fresh every hour" : selected.ring === 1 ? "Set once, held long" : `${selected.tempo} cadence`;

  const handleSelect = (ring: RingIndex) => {
    setSelectedRing(ring);
    onRingChange?.(RINGS[ring]);
  };

  const rootStyle: CSSProperties = {
    minHeight: "100%",
    padding: 24,
    background:
      "radial-gradient(circle at top, rgba(212,165,116,0.12), transparent 36%), radial-gradient(circle at 80% 20%, rgba(126,184,201,0.10), transparent 30%), linear-gradient(180deg, #09090d 0%, #111117 100%)",
    color: "#efe7db",
    fontFamily: "system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",
  };

  const cardStyle: CSSProperties = {
    background: "rgba(21, 22, 28, 0.9)",
    border: "1px solid rgba(255,255,255,0.08)",
    borderRadius: 22,
    boxShadow: "0 20px 50px rgba(0,0,0,0.24)",
  };

  return (
    <div style={rootStyle}>
      <div style={{ maxWidth: 1280, margin: "0 auto", display: "grid", gap: 18 }}>
        <section style={{ ...cardStyle, padding: 22 }}>
          <div style={{ display: "flex", justifyContent: "space-between", gap: 18, flexWrap: "wrap", alignItems: "flex-start" }}>
            <div style={{ flex: 1, minWidth: 280 }}>
              <div style={{ fontSize: 12, letterSpacing: "0.14em", textTransform: "uppercase", color: "#9ca3af" }}>Cascade / Ring System</div>
              <h1 style={{ margin: "8px 0 8px", fontSize: 34, lineHeight: 1.05, color: "#f6d9b3" }}>{title}</h1>
              <p style={{ margin: 0, color: "#ada8b6", maxWidth: 840, fontSize: 15, lineHeight: 1.55 }}>{subtitle}</p>
            </div>

            <div style={{ minWidth: 300, maxWidth: 380, flex: 1, padding: 16, borderRadius: 18, background: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.08)" }}>
              <div style={{ display: "flex", justifyContent: "space-between", gap: 12, alignItems: "baseline" }}>
                <div>
                  <div style={{ fontSize: 12, color: "#9ca3af", letterSpacing: "0.12em", textTransform: "uppercase" }}>Capacity</div>
                  <div style={{ fontSize: 22, fontWeight: 700 }}>{filledCapacity}/{totalCapacity} outer nodes</div>
                </div>
                <div style={{ textAlign: "right" }}>
                  <div style={{ fontSize: 12, color: "#9ca3af", letterSpacing: "0.12em", textTransform: "uppercase" }}>Selected ring</div>
                  <div style={{ fontSize: 22, fontWeight: 700, color: selected.color }}>{selected.name}</div>
                </div>
              </div>
              <div style={{ marginTop: 12, height: 10, borderRadius: 999, background: "rgba(255,255,255,0.08)", overflow: "hidden" }}>
                <div
                  style={{
                    width: ringFillWidth(filledCapacity, totalCapacity),
                    height: "100%",
                    borderRadius: 999,
                    background: "linear-gradient(90deg, #d4a574 0%, #7eb8c9 50%, #d4a8b4 100%)",
                    transition: "width 220ms ease",
                  }}
                />
              </div>
              <div style={{ marginTop: 10, color: "#c2b7a8", fontSize: 13, lineHeight: 1.5 }}>
                Room for 126. Grown from 6. Every ring turns on its own tempo.
              </div>
            </div>
          </div>
        </section>

        <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.18fr) minmax(340px, 0.82fr)", gap: 18, alignItems: "start" }}>
          <div style={{ display: "grid", gap: 18 }}>
            <section style={{ ...cardStyle, padding: 18 }}>
              <div style={{ display: "flex", justifyContent: "space-between", gap: 12, flexWrap: "wrap", alignItems: "center", marginBottom: 14 }}>
                <div>
                  <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>Select a ring</div>
                  <h2 style={{ margin: "6px 0 0", fontSize: 22 }}>{selected.name}</h2>
                </div>
                <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
                  {RINGS.map((ring) => {
                    const active = ring.ring === selectedRing;
                    return (
                      <button
                        key={ring.ring}
                        type="button"
                        onClick={() => handleSelect(ring.ring)}
                        style={{
                          borderRadius: 999,
                          border: active ? `1px solid ${ring.color}66` : "1px solid rgba(255,255,255,0.12)",
                          background: active ? `${ring.color}22` : "rgba(255,255,255,0.04)",
                          color: active ? ring.color : "#efe7db",
                          padding: "8px 12px",
                          fontSize: 12,
                          cursor: "pointer",
                          fontWeight: active ? 700 : 500,
                        }}
                      >
                        R{ring.ring}
                      </button>
                    );
                  })}
                </div>
              </div>

              <div style={{ borderRadius: 18, overflow: "hidden", border: "1px solid rgba(255,255,255,0.08)", background: "rgba(10, 10, 14, 0.72)" }}>
                <HexLattice nodes={previewNodes} showLabels={selectedRing === 6} size="full" activeNodeId={selectedRing === 0 ? "ring-center" : `ring-${selectedRing}-0`} />
              </div>

              <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(160px, 1fr))", gap: 10, marginTop: 14 }}>
                <StatTile label="Size" value={`${selected.size}`} detail={`${selected.root} root · ${selected.tempo} tempo`} tone={selected.color} />
                <StatTile label="Filled" value={`${selectedCount}`} detail={`${selectedFill}% of this ring`} tone={selected.color} />
                <StatTile label={dimmedLabel} value={`${dimmedSlots}`} detail={selectedRing === 1 ? "Markers for dissolved or dormant claims." : "Empty slots wait as part of the lattice."} tone={selected.color} />
                <StatTile label="Assignment" value={selected.assignment} detail={activeTempo} tone={selected.color} />
                <StatTile label="Sees" value={selected.sees} detail={selected.summary} tone={selected.color} />
              </div>
            </section>

            <section style={{ ...cardStyle, padding: 18 }}>
              <div style={{ display: "flex", justifyContent: "space-between", gap: 12, flexWrap: "wrap", alignItems: "center", marginBottom: 12 }}>
                <div>
                  <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>Gravity ladder</div>
                  <h3 style={{ margin: "6px 0 0", fontSize: 22 }}>How people rise through the lattice</h3>
                </div>
                <div style={{ color: "#c2b7a8", fontSize: 13 }}>R6 is hourly. R1 is mutual and nearly permanent.</div>
              </div>

              <div style={{ display: "grid", gap: 10 }}>
                {RINGS.slice(1).map((ring) => {
                  const ringActive = ring.ring === selectedRing;
                  const meta = RING_MECHANICS[ring.ring];

                  return (
                    <div
                      key={ring.ring}
                      style={{
                        borderRadius: 16,
                        padding: 14,
                        background: ringActive ? `${ring.color}14` : "rgba(255,255,255,0.03)",
                        border: ringActive ? `1px solid ${ring.color}66` : "1px solid rgba(255,255,255,0.08)",
                      }}
                    >
                      <div style={{ display: "flex", justifyContent: "space-between", gap: 12, alignItems: "baseline", flexWrap: "wrap" }}>
                        <div>
                          <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>R{ring.ring} · {ring.tempo}</div>
                          <div style={{ marginTop: 4, fontWeight: 700, color: ring.color }}>{ring.name}</div>
                        </div>
                        <div style={{ color: "#d8d0c2", fontSize: 13 }}>{ring.assignment}</div>
                      </div>
                      <div style={{ marginTop: 8, color: "#b6ac9d", fontSize: 13, lineHeight: 1.55 }}>{meta.trigger}</div>
                      <div style={{ marginTop: 8, display: "flex", flexWrap: "wrap", gap: 8 }}>
                        <span style={{ borderRadius: 999, padding: "6px 10px", fontSize: 12, background: `${ring.color}18`, color: "#f7efe2", border: `1px solid ${ring.color}44` }}>Root {ring.root}</span>
                        <span style={{ borderRadius: 999, padding: "6px 10px", fontSize: 12, background: "rgba(255,255,255,0.04)", color: "#f7efe2", border: "1px solid rgba(255,255,255,0.12)" }}>{meta.persistence}</span>
                        <span style={{ borderRadius: 999, padding: "6px 10px", fontSize: 12, background: "rgba(255,255,255,0.04)", color: "#f7efe2", border: "1px solid rgba(255,255,255,0.12)" }}>{meta.governance}</span>
                      </div>
                    </div>
                  );
                })}
              </div>
            </section>
          </div>

          <aside style={{ display: "grid", gap: 18 }}>
            <section style={{ ...cardStyle, padding: 18 }}>
              <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>Selected ring</div>
              <div style={{ marginTop: 12, display: "flex", gap: 14, alignItems: "center" }}>
                <div
                  style={{
                    width: 64,
                    height: 64,
                    borderRadius: 18,
                    display: "grid",
                    placeItems: "center",
                    background: `${selected.color}22`,
                    border: `1px solid ${selected.color}55`,
                    color: selected.color,
                    fontSize: 20,
                    fontWeight: 800,
                  }}
                >
                  R{selected.ring}
                </div>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: 24, fontWeight: 800, lineHeight: 1.05 }}>{selected.name}</div>
                  <div style={{ color: "#a6a0b1", fontSize: 13, marginTop: 4 }}>{selected.summary}</div>
                </div>
              </div>

              <div style={{ display: "grid", gap: 10, marginTop: 16 }}>
                <InfoRow label="Tempo" value={selected.tempo} tone={selected.color} />
                <InfoRow label="Assignment" value={selected.assignment} tone={selected.color} />
                <InfoRow label="Root" value={selected.root} tone={selected.color} />
                <InfoRow label="Sees" value={selected.sees} tone={selected.color} />
                <InfoRow label={dimmedLabel} value={`${dimmedSlots}`} tone={selected.color} />
              </div>

              <div style={{ marginTop: 16 }}>
                <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>Mechanics</div>
                <div style={{ display: "grid", gap: 10, marginTop: 10 }}>
                  <MechanicRow label="Trigger" value={mechanics.trigger} tone={selected.color} />
                  <MechanicRow label="Persistence" value={mechanics.persistence} tone={selected.color} />
                  <MechanicRow label="Governance" value={mechanics.governance} tone={selected.color} />
                </div>
              </div>
            </section>

            <section style={{ ...cardStyle, padding: 18 }}>
              <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>What the ring means</div>
              <div style={{ marginTop: 10, display: "grid", gap: 10 }}>
                <DetailCard title="Selection" text="Tap any ring to focus the lattice. The preview fills that ring so you can see the scale and tempo in context." />
                <DetailCard title="Permanence" text="R1 is nearly permanent. R2-R6 can demote or refresh on their own cadence. The ring map keeps that truth visible." />
                <DetailCard title="Ghost slots" text={selectedRing === 1 ? "Dim hexes mark the places that were claimed and then released. They stay visible as history." : "Empty slots stay visible in the lattice so the ring never forgets what it can still hold."} />
                <DetailCard title="Discovery" text="R6 is the current atmosphere: hourly, ambient, and ephemeral. It is the surface you open first." />
              </div>
            </section>

            <section style={{ ...cardStyle, padding: 18 }}>
              <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>Tempo ladder</div>
              <div style={{ marginTop: 10, display: "grid", gap: 10 }}>
                <LadderRow from="R6" to="R5" label="Hourly → Daily" tone={toneForRing(6)} detail="The Current condenses into the Wave when a day of signal holds." />
                <LadderRow from="R5" to="R4" label="Daily → Weekly" tone={toneForRing(5)} detail="The Wave becomes Echo when creative reflection stays consistent." />
                <LadderRow from="R4" to="R3" label="Weekly → Monthly" tone={toneForRing(4)} detail="Echo can become Longing when the pattern deepens into season." />
                <LadderRow from="R3" to="R2" label="Monthly → Quarterly" tone={toneForRing(3)} detail="Longing can become Archetype when a role is repeatedly confirmed." />
                <LadderRow from="R2" to="R1" label="Quarterly → Yearly" tone={toneForRing(2)} detail="Archetypes rise only with mutual claim and real staying power." />
              </div>
            </section>
          </aside>
        </div>
      </div>
    </div>
  );
}

function StatTile({ label, value, detail, tone }: { label: string; value: string; detail: string; tone: string }) {
  return (
    <div style={{ borderRadius: 16, padding: 14, background: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.08)" }}>
      <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>{label}</div>
      <div style={{ marginTop: 6, fontSize: 20, fontWeight: 800, color: tone, lineHeight: 1.1 }}>{value}</div>
      <div style={{ marginTop: 6, color: "#b6ac9d", fontSize: 13, lineHeight: 1.45 }}>{detail}</div>
    </div>
  );
}

function InfoRow({ label, value, tone }: { label: string; value: string; tone: string }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", gap: 12, alignItems: "center", padding: "10px 12px", borderRadius: 14, background: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.08)" }}>
      <div style={{ color: "#c8bfaf", fontSize: 14 }}>{label}</div>
      <div style={{ color: tone, fontWeight: 800, fontSize: 14 }}>{value}</div>
    </div>
  );
}

function DetailCard({ title, text }: { title: string; text: string }) {
  return (
    <div style={{ borderRadius: 16, padding: 12, background: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.08)" }}>
      <div style={{ fontSize: 12, color: "#9ca3af", textTransform: "uppercase", letterSpacing: "0.12em" }}>{title}</div>
      <div style={{ marginTop: 6, color: "#d8d0c2", fontSize: 14, lineHeight: 1.55 }}>{text}</div>
    </div>
  );
}

function MechanicRow({ label, value, tone }: { label: string; value: string; tone: string }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "auto 1fr", gap: 10, alignItems: "center", padding: "10px 12px", borderRadius: 14, background: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.08)" }}>
      <div style={{ fontWeight: 700, color: tone }}>{label}</div>
      <div style={{ color: "rgba(247,239,226,0.72)", fontSize: 12, lineHeight: 1.45 }}>{value}</div>
    </div>
  );
}

function LadderRow({ from, to, label, detail, tone }: { from: string; to: string; label: string; detail: string; tone: string }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "auto auto 1fr", gap: 10, alignItems: "start", padding: 12, borderRadius: 16, background: "rgba(255,255,255,0.03)", border: "1px solid rgba(255,255,255,0.08)" }}>
      <div style={{ color: tone, fontWeight: 800, minWidth: 32 }}>{from}</div>
      <div style={{ color: "#f7efe2", fontWeight: 800 }}>→</div>
      <div>
        <div style={{ display: "flex", justifyContent: "space-between", gap: 12, flexWrap: "wrap", alignItems: "baseline" }}>
          <div style={{ fontWeight: 700 }}>{to} · {label}</div>
          <div style={{ fontSize: 11, color: "rgba(247,239,226,0.55)", textTransform: "uppercase", letterSpacing: "0.08em" }}>{directionLabel(Number(to.slice(1)) as RingIndex)}</div>
        </div>
        <div style={{ marginTop: 6, color: "#d8d0c2", fontSize: 13, lineHeight: 1.5 }}>{detail}</div>
      </div>
    </div>
  );
}
