/* veil-messages.jsx — Messages list + Chat detail */
/* eslint-disable no-undef */

const THREADS = [
  {
    id: "t1",
    nick: "The Philosopher",
    preview: "if attention is a form of love, what are we doing to each other in here…",
    time: "now",
    unread: 2,
    typing: true,
    hue: 295,
  },
  {
    id: "t2",
    nick: null,
    preview: "you wrote something last week i haven't stopped thinking about",
    time: "12m",
    unread: 1,
    hue: 248,
  },
  {
    id: "t3",
    nick: "Late Night Thinker",
    preview: "3am again. trade you a confession for a confession?",
    time: "1h",
    unread: 0,
    hue: 200,
  },
  {
    id: "t4",
    nick: "The Girl with Weird Theories",
    preview: "ok so what if memory isn't storage, it's a loop we keep re-rendering—",
    time: "3h",
    unread: 0,
    hue: 320,
  },
  {
    id: "t5",
    nick: null,
    preview: "resonated with your thought on stillness. wanted to say it directly.",
    time: "yest",
    unread: 0,
    hue: 248,
    resonated: true,
  },
  {
    id: "t6",
    nick: "Smart Anonymous",
    preview: "you read Bachelard's poetics of space? whole chapter on attics—",
    time: "2d",
    unread: 0,
    hue: 270,
  },
  {
    id: "t7",
    nick: null,
    preview: "hi. don't know you. felt like saying hello to no one in particular.",
    time: "3d",
    unread: 0,
    hue: 230,
  },
];

const CHAT_MESSAGES = [
  { side: "them", text: "you up?", time: "3:38 AM" },
  { side: "them", text: "I've been turning your last post over for an hour. the one about stillness." },
  { side: "me",   text: "still here. half awake. what about it." },
  { side: "them", text: "if attention is a form of love, what are we doing to each other in feeds?" },
  { side: "me",   text: "honestly? a kind of communal looking away." },
  { side: "them", text: "yeah." },
  { side: "them", text: "i think this is the first place i've felt looked-at without being seen." },
  { side: "me",   text: "that's the whole pitch isn't it" },
  { side: "typing" },
];

function VeilChatRow({ thread, onOpen }) {
  const display = thread.nick || "Anonymous";
  const isAnon = !thread.nick;
  return (
    <button onClick={() => onOpen(thread)}
            style={{
              width: "100%", display: "flex", alignItems: "center", gap: 14,
              padding: "12px 18px",
              textAlign: "left",
              borderBottom: "1px solid oklch(0.20 0.008 270 / 0.6)",
            }}>
      <div style={{
        width: 44, height: 44, borderRadius: 14,
        background: `radial-gradient(circle at 30% 30%, oklch(0.30 0.05 ${thread.hue}), oklch(0.16 0.008 270))`,
        border: "1px solid var(--veil-hairline)",
        display: "flex", alignItems: "center", justifyContent: "center",
        position: "relative", flexShrink: 0,
      }}>
        <VeilSigil seed={thread.id} size={36} hue={thread.hue}/>
        {thread.unread > 0 && (
          <span style={{
            position: "absolute", top: -3, right: -3,
            minWidth: 16, height: 16, padding: "0 5px",
            borderRadius: 999, background: "var(--veil-violet)",
            boxShadow: "0 0 10px oklch(0.62 0.17 295 / 0.6)",
            fontSize: 9.5, fontFamily: "var(--veil-font-mono)",
            display: "flex", alignItems: "center", justifyContent: "center",
            color: "white", fontWeight: 500, letterSpacing: 0,
          }}>{thread.unread}</span>
        )}
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: "flex", alignItems: "baseline", gap: 8, minWidth: 0 }}>
          <span style={{
            fontSize: 15,
            fontWeight: isAnon ? 400 : 600,
            color: isAnon ? "var(--veil-text)" : "var(--veil-blue)",
            fontFamily: "var(--veil-font-ui)",
            letterSpacing: isAnon ? "-0.005em" : "0.005em",
            whiteSpace: "nowrap",
            overflow: "hidden",
            textOverflow: "ellipsis",
            flex: "0 1 auto",
            minWidth: 0,
          }}>{display}</span>
          {thread.resonated && (
            <span style={{
              fontFamily: "var(--veil-font-mono)", fontSize: 9,
              letterSpacing: "0.1em", textTransform: "uppercase",
              color: "var(--veil-cyan)",
              flexShrink: 0,
            }}>resonated</span>
          )}
          <span className="veil-meta" style={{ marginLeft: "auto", fontSize: 10.5, flexShrink: 0 }}>{thread.time}</span>
        </div>
        <div className="veil-body" style={{
          marginTop: 2,
          fontSize: 13.5,
          fontWeight: 400,
          color: thread.unread > 0 ? "var(--veil-text-soft)" : "var(--veil-muted)",
          overflow: "hidden",
          textOverflow: "ellipsis",
          whiteSpace: "nowrap",
        }}>
          {thread.typing
            ? <span style={{ color: "var(--veil-blue)", fontFamily: "var(--veil-font-ui)", fontWeight: 500 }}>typing…</span>
            : thread.preview}
        </div>
      </div>
    </button>
  );
}

function VeilMessages({ onTabChange, active, onOpenThread }) {
  const [filter, setFilter] = React.useState("all");
  const filtered = filter === "kept"
    ? THREADS.filter(t => t.nick)
    : THREADS;

  return (
    <div className="veil-app" style={{ position: "relative", height: "100%", overflow: "hidden" }}>
      <div className="veil-ambient"/>
      <div className="veil-scroll" style={{
        position: "relative", zIndex: 1,
        height: "100%", overflowY: "auto",
        paddingTop: 44, paddingBottom: 110,
      }}>
        <VeilHeader
          left={<span style={{ fontSize: 17, color: "var(--veil-text)", fontWeight: 600, letterSpacing: "-0.005em", textTransform: "lowercase" }}>inbox</span>}
          right={<>
            <button><VeilIcon name="compose" size={20} color="var(--veil-text-soft)"/></button>
          </>}
          title="quiet rooms"
          sub="14 ongoing · 3 with private names"
        />

        {/* segmented filter */}
        <div style={{ padding: "10px 18px 14px" }}>
          <div style={{
            display: "grid", gridTemplateColumns: "1fr 1fr 1fr",
            background: "oklch(0.17 0.008 270)",
            border: "1px solid var(--veil-hairline)",
            borderRadius: 12, padding: 3, position: "relative",
          }}>
            {[
              { k: "all", label: "All" },
              { k: "kept", label: "Kept names" },
              { k: "new", label: "New" },
            ].map(s => (
              <button key={s.k} onClick={() => setFilter(s.k)}
                      style={{
                        padding: "8px 0",
                        fontSize: 12.5,
                        letterSpacing: "-0.005em",
                        color: filter === s.k ? "var(--veil-text)" : "var(--veil-muted)",
                        background: filter === s.k ? "oklch(0.22 0.010 270)" : "transparent",
                        borderRadius: 9,
                        transition: "all 0.18s",
                      }}>{s.label}</button>
            ))}
          </div>
        </div>

        <div>
          {filtered.map(t => <VeilChatRow key={t.id} thread={t} onOpen={onOpenThread}/>)}
        </div>

        <div style={{
          padding: "20px 18px",
          textAlign: "center",
        }}>
          <div className="veil-meta" style={{ color: "var(--veil-subtle)" }}>
            requests open · 4 strangers waiting
          </div>
        </div>
      </div>

      <VeilTabBar active={active} onChange={onTabChange}/>
    </div>
  );
}

// ──────────────────────────────────────────────────────────
// Chat detail
// ──────────────────────────────────────────────────────────
function VeilChat({ thread, onBack, onTabChange, active }) {
  const display = thread?.nick || "Anonymous";
  const isAnon = !thread?.nick;
  const hue = thread?.hue || 248;
  const [draft, setDraft] = React.useState("");
  const [editingNick, setEditingNick] = React.useState(false);
  const [nick, setNick] = React.useState(thread?.nick || "");

  return (
    <div className="veil-app" style={{ position: "relative", height: "100%", overflow: "hidden" }}>
      <div className="veil-ambient"/>

      {/* header */}
      <div style={{
        position: "absolute", top: 0, left: 0, right: 0, zIndex: 30,
        paddingTop: 50, paddingBottom: 12,
        background: "linear-gradient(180deg, oklch(0.14 0.006 270 / 0.95), transparent)",
        backdropFilter: "blur(18px)", WebkitBackdropFilter: "blur(18px)",
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "0 12px 8px" }}>
          <button onClick={onBack} style={{ padding: "6px" }}>
            <VeilIcon name="back" size={22} color="var(--veil-text-soft)"/>
          </button>
          <div style={{
            width: 36, height: 36, borderRadius: 11,
            background: `radial-gradient(circle at 30% 30%, oklch(0.30 0.06 ${hue}), oklch(0.16 0.008 270))`,
            border: "1px solid var(--veil-hairline)",
            display: "flex", alignItems: "center", justifyContent: "center",
          }}>
            <VeilSigil seed={thread?.id || "x"} size={28} hue={hue}/>
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{
              fontSize: 16,
              fontFamily: "var(--veil-font-ui)",
              fontWeight: isAnon ? 500 : 600,
              letterSpacing: isAnon ? "-0.005em" : "0.01em",
              color: isAnon ? "var(--veil-text)" : "var(--veil-blue)",
            }}>{display}</div>
            <div className="veil-meta" style={{ fontSize: 9.5, marginTop: 2, display: "flex", alignItems: "center", gap: 5 }}>
              <VeilIcon name="lock" size={10}/> end-to-end · private nickname
            </div>
          </div>
          <button style={{ padding: 6 }}>
            <VeilIcon name="more" size={20} color="var(--veil-text-soft)"/>
          </button>
        </div>
      </div>

      {/* messages */}
      <div className="veil-scroll" style={{
        position: "relative", zIndex: 1,
        height: "100%", overflowY: "auto",
        paddingTop: 112, paddingBottom: 170,
        display: "flex", flexDirection: "column", gap: 6,
      }}>
        {/* private nickname pill — distinct intimate moment */}
        <div style={{ display: "flex", justifyContent: "center", margin: "8px 16px 16px" }}>
          <div style={{
            display: "inline-flex", alignItems: "center", gap: 8,
            padding: "8px 14px",
            borderRadius: 999,
            background: "oklch(0.19 0.008 270 / 0.7)",
            border: "1px solid oklch(0.62 0.17 295 / 0.30)",
            boxShadow: "0 0 18px -8px oklch(0.62 0.17 295 / 0.5)",
          }}>
            <VeilIcon name="lock" size={11} color="var(--veil-violet)"/>
            <span className="veil-meta" style={{ fontSize: 10, color: "var(--veil-muted)", letterSpacing: "0.08em" }}>
              Only you see this name ·
            </span>
            {editingNick ? (
              <input value={nick} autoFocus
                     onChange={e => setNick(e.target.value)}
                     onBlur={() => setEditingNick(false)}
                     style={{
                       width: 130,
                       fontFamily: "var(--veil-font-display)",
                       fontWeight: 600, fontSize: 13,
                       letterSpacing: "0.02em",
                       color: "var(--veil-blue)",
                     }}/>
            ) : (
              <button onClick={() => setEditingNick(true)}
                      style={{
                        fontFamily: "var(--veil-font-display)",
                        fontWeight: 600, fontSize: 13,
                        letterSpacing: "0.02em",
                        color: "var(--veil-blue)",
                      }}>
                {nick || "tap to name them"}
              </button>
            )}
          </div>
        </div>

        {/* day separator */}
        <div style={{
          textAlign: "center", padding: "4px 0 10px",
        }}>
          <span className="veil-meta" style={{ color: "var(--veil-subtle)" }}>Tonight · 3:38 AM</span>
        </div>

        {CHAT_MESSAGES.map((m, i) => <Bubble key={i} m={m} hue={hue}/>)}

        <div style={{ height: 20 }}/>
      </div>

      {/* composer */}
      <div style={{
        position: "absolute", bottom: 90, left: 0, right: 0, zIndex: 35,
        padding: "0 14px",
      }}>
        <div style={{
          display: "flex", alignItems: "center", gap: 8,
          padding: "8px 8px 8px 16px",
          background: "oklch(0.17 0.008 270 / 0.92)",
          border: "1px solid var(--veil-hairline)",
          borderRadius: 22,
          backdropFilter: "blur(18px)",
        }}>
          <input value={draft}
                 onChange={e => setDraft(e.target.value)}
                 placeholder="speak quietly…"
                 style={{
                   flex: 1,
                   fontSize: 14.5,
                   color: "var(--veil-text)",
                   "::placeholder": { color: "var(--veil-subtle)" },
                 }}/>
          <button style={{
            width: 34, height: 34, borderRadius: 999,
            display: "flex", alignItems: "center", justifyContent: "center",
            background: draft ? "var(--veil-blue)" : "oklch(0.22 0.008 270)",
            color: draft ? "white" : "var(--veil-subtle)",
            transition: "all 0.2s",
            boxShadow: draft ? "0 0 14px -2px var(--veil-blue)" : "none",
          }}>
            <VeilIcon name="arrow-up" size={16} color="currentColor" strokeWidth={2}/>
          </button>
        </div>
      </div>

      <VeilTabBar active={active} onChange={onTabChange}/>
    </div>
  );
}

function Bubble({ m, hue }) {
  if (m.side === "typing") {
    return (
      <div style={{ padding: "4px 18px", display: "flex" }}>
        <div style={{
          display: "inline-flex", gap: 4,
          padding: "10px 14px",
          borderRadius: "16px 16px 16px 4px",
          background: "oklch(0.20 0.008 270)",
          border: "1px solid var(--veil-hairline)",
        }}>
          {[0, 1, 2].map(i => (
            <span key={i} style={{
              width: 6, height: 6, borderRadius: "50%",
              background: "var(--veil-muted)",
              animation: `veilDot 1.2s ${i * 0.15}s infinite`,
            }}/>
          ))}
        </div>
        <style>{`@keyframes veilDot { 0%, 60%, 100% { opacity: 0.3; transform: translateY(0); } 30% { opacity: 1; transform: translateY(-3px); } }`}</style>
      </div>
    );
  }
  const mine = m.side === "me";
  return (
    <div style={{
      padding: "1px 14px",
      display: "flex", justifyContent: mine ? "flex-end" : "flex-start",
    }}>
      <div style={{ maxWidth: "82%", display: "flex", flexDirection: "column", alignItems: mine ? "flex-end" : "flex-start" }}>
        <div className="veil-body" style={{
          padding: "10px 14px",
          fontSize: 14.5,
          fontWeight: 400,
          color: mine ? "var(--veil-text)" : "var(--veil-text-soft)",
          background: mine
            ? "linear-gradient(135deg, oklch(0.30 0.10 250), oklch(0.26 0.12 270))"
            : "oklch(0.19 0.008 270)",
          border: mine ? "1px solid oklch(0.74 0.14 248 / 0.35)" : "1px solid var(--veil-hairline)",
          borderRadius: mine ? "16px 16px 4px 16px" : "16px 16px 16px 4px",
          boxShadow: mine ? "0 0 18px -10px oklch(0.74 0.14 248 / 0.6)" : "none",
          textWrap: "pretty",
        }}>{m.text}</div>
        {m.time && (
          <div className="veil-meta" style={{ marginTop: 4, fontSize: 9.5, color: "var(--veil-subtle)" }}>
            {m.time}
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { VeilMessages, VeilChat, VeilChatRow });
