/* ============================================================================
   Variant — CHAT-LED HOME (Direction 3 from wireframes)
   The conversation is the headline. Below the chat, a single-scroll
   "skim me" appendix: Work list → Projects grid → Contact line.

   Visual system inherits Refined's tokens (palette, font, name size).
   ========================================================================= */

(() => {
  const { useState, useEffect, useRef } = React;
  const { SITE, useChat, useRouter, ContactDropdown } = window;

  function renderMarkdown(text) {
    const parts = [];
    const pattern = /\[([^\]]+)\]\((https?:\/\/[^)]+)\)|\*\*([^*]+)\*\*|\*([^*]+)\*/g;
    let last = 0, match, key = 0;
    while ((match = pattern.exec(text)) !== null) {
      if (match.index > last) parts.push(text.slice(last, match.index));
      if (match[1] && match[2]) {
        parts.push(<a key={key++} href={match[2]} target="_blank" rel="noopener noreferrer" style={{ color: "inherit", textDecorationColor: "currentColor" }}>{match[1]}</a>);
      } else if (match[3]) {
        parts.push(<strong key={key++}>{match[3]}</strong>);
      } else if (match[4]) {
        parts.push(<em key={key++}>{match[4]}</em>);
      }
      last = pattern.lastIndex;
    }
    if (last < text.length) parts.push(text.slice(last));
    return parts;
  }
  const {
    useTweaks, TweaksPanel, TweakSection,
    TweakColor, TweakSelect, TweakSlider, TweakText, TweakRadio,
  } = window;

  /* Curated palettes — [bg, fg, muted, accent]. Match Refined. */
  const PALETTES = [
    ["#f5f0ea", "#34302b", "#8a8079", "#b08968"], // warm cream (default)
    ["#efe7da", "#2d2924", "#857c72", "#9c6b3f"], // deeper sand
    ["#eef0eb", "#262a26", "#7c857c", "#6b8b6b"], // sage
    ["#f7f5f1", "#1f1d1b", "#7a7570", "#3a3a3a"], // bone, charcoal
    ["#ffffff", "#0a0a0a", "#8a8a8a", "#0a0a0a"], // stark
  ];

  const FONT_OPTIONS = [
    { value: "Newsreader",         label: "Newsreader · serif"          },
    { value: "Instrument Serif",   label: "Instrument Serif · serif"    },
    { value: "Source Serif 4",     label: "Source Serif 4 · serif"      },
    { value: "EB Garamond",        label: "EB Garamond · serif"         },
    { value: "Cormorant Garamond", label: "Cormorant Garamond · serif"  },
    { value: "Nunito",             label: "Nunito · rounded sans"       },
    { value: "Quicksand",          label: "Quicksand · rounded sans"    },
    { value: "Sora",               label: "Sora · soft sans"            },
    { value: "Mulish",             label: "Mulish · soft sans"          },
    { value: "Figtree",            label: "Figtree · soft sans"         },
  ];
  const SERIF_FALLBACK = 'Georgia, "Times New Roman", serif';
  const SANS_FALLBACK  = '"Helvetica Neue", Helvetica, Arial, sans-serif';
  const SANS_FONTS = new Set(["Nunito", "Quicksand", "Sora", "Mulish", "Figtree"]);
  const fontStack = (name) => {
    const fallback = SANS_FONTS.has(name) ? SANS_FALLBACK : SERIF_FALLBACK;
    return `"${name}", ${fallback}`;
  };

  /* Reuse the shared tweak defaults so the user's palette/font choice
     carries over from Refined. nameSize gets a smaller default since this
     layout doesn't lean on a giant name. */
  const SHARED_DEFAULTS = (window.TWEAK_DEFAULTS) || {};
  const TWEAK_DEFAULTS = {
    palette: PALETTES[0],
    font: "Newsreader",
    nameSize: 60,
    nameWeight: "500",
    tagline: "Pick my brain.",
    chatLayout: "pinned",
    ...SHARED_DEFAULTS,
    // override nameSize for chat-led even if shared defaults set a bigger
    // value — the hero name lives next to a chat input, not as a billboard.
    nameSize: Math.min(SHARED_DEFAULTS.nameSize || 60, 72),
  };

  const SUGGESTED = [
    "What's your working style?",
    "Strongest project at Moveworks?",
    "Why should we hire you?",
    "What are you looking for next?",
  ];

  /* ----------------------------------------------------------------------- */

  const buildStyles = (t) => {
    const [BG, FG, MUTED, ACCENT] = t.palette;
    const HAIRLINE = "rgba(0,0,0,0.10)";
    const FONT = fontStack(t.font);

    const nameFontSize = `clamp(40px, ${Math.max(5, t.nameSize / 12)}vw, ${t.nameSize}px)`;

    return {
      root: {
        minHeight: "100vh",
        background: BG,
        color: FG,
        fontFamily: FONT,
        fontWeight: 400,
        lineHeight: 1.5,
        transition: "background-color 240ms ease, color 240ms ease",
      },

      /* ── hero: chat is the headline ────────────────────────────────── */
      hero: {
        height: "100vh",
        display: "flex", flexDirection: "column",
        padding: "40px 32px 32px",
        maxWidth: 880, margin: "0 auto",
        boxSizing: "border-box",
        overflow: "hidden",
      },
      heroIntro: {
        marginBottom: 36,
      },
      nameRow: {
        display: "flex",
        alignItems: "center",
        gap: 16,
        marginBottom: 12,
      },
      avatarWrap: {
        width: nameFontSize,
        height: nameFontSize,
        flexShrink: 0,
        borderRadius: "50%",
        overflow: "hidden",
        border: `2px solid ${HAIRLINE}`,
      },
      avatar: {
        width: "100%",
        height: "100%",
        objectFit: "cover",
        display: "block",
      },
      heroName: {
        fontSize: nameFontSize,
        lineHeight: 1, letterSpacing: "-0.02em",
        margin: 0,
        fontWeight: t.nameWeight || 500,
        color: FG,
      },
      heroTagline: {
        fontSize: "clamp(18px, 1.8vw, 22px)",
        color: MUTED, fontStyle: "italic",
        marginTop: 12, marginBottom: 0,
        letterSpacing: "-0.005em",
      },

      /* Chat conversation transcript */
      chatThread: {
        flex: 1,
        minHeight: 0,
        marginBottom: 20,
        overflowY: "auto",
        display: "flex", flexDirection: "column", gap: 14,
        fontSize: 18, lineHeight: 1.55,
      },
      chatEmpty: {
        color: MUTED, fontStyle: "italic",
        fontSize: 16,
        padding: "10px 2px",
      },
      chatBubbleUser: {
        alignSelf: "flex-end",
        maxWidth: "75%",
        background: `color-mix(in oklab, ${FG} 6%, ${BG})`,
        border: `1px solid ${HAIRLINE}`,
        borderRadius: 14,
        padding: "10px 14px",
        color: FG,
        fontSize: 17,
      },
      chatBubbleBot: {
        alignSelf: "flex-start",
        maxWidth: "92%",
        color: FG,
        fontSize: 19, lineHeight: 1.55,
      },
      chatThinking: {
        color: MUTED, fontStyle: "italic", fontSize: 17,
      },
      chatError: { color: "#a33", fontSize: 14, marginTop: 4 },

      /* Chat input — the centerpiece */
      chatInputWrap: {
        display: "flex",
        alignItems: "center",
        gap: 0,
        background: BG,
        border: `1.5px solid ${FG}`,
        borderRadius: 14,
        padding: "6px 6px 6px 22px",
        boxShadow: "0 1px 0 rgba(0,0,0,0.02), 0 18px 40px rgba(0,0,0,0.05)",
        transition: "box-shadow 200ms ease, border-color 200ms ease",
      },
      chatInput: {
        flex: 1,
        appearance: "none", border: 0, outline: 0, background: "transparent",
        padding: "16px 8px",
        fontSize: 19, fontFamily: FONT, color: FG,
        lineHeight: 1.3,
        resize: "none",
      },
      chatSend: {
        appearance: "none", border: 0,
        background: FG, color: BG,
        width: 44, height: 44, borderRadius: 10,
        cursor: "pointer",
        fontSize: 20, lineHeight: 1,
        display: "flex", alignItems: "center", justifyContent: "center",
        transition: "opacity 160ms ease",
      },

      /* Suggested prompts */
      promptsRow: {
        marginTop: 18,
        display: "flex", flexWrap: "wrap", gap: 8,
      },
      promptChip: {
        appearance: "none",
        background: "transparent",
        border: `1px solid ${HAIRLINE}`,
        borderRadius: 999,
        padding: "8px 14px",
        fontFamily: FONT,
        fontSize: 15,
        color: MUTED,
        cursor: "pointer",
        transition: "background 160ms ease, color 160ms ease, border-color 160ms ease",
      },

      /* "scroll for the facts" hint */
      scrollHint: {
        marginTop: 56,
        fontSize: 14, color: MUTED,
        letterSpacing: "0.08em", textTransform: "uppercase",
        fontFamily: FONT,
        display: "flex", alignItems: "center", gap: 10,
      },

      /* ── shared section styles for Work/Projects/Contact ───────────── */
      section: {
        maxWidth: 880, margin: "0 auto",
        padding: "120px 32px 0",
        boxSizing: "border-box",
      },
      sectionLast: {
        maxWidth: 880, margin: "0 auto",
        padding: "120px 32px 120px",
        boxSizing: "border-box",
      },
      sectionLabel: {
        fontSize: 13, letterSpacing: "0.18em", textTransform: "uppercase",
        color: MUTED,
        marginBottom: 28,
      },
      sectionHeading: {
        fontSize: 36, letterSpacing: "-0.015em",
        margin: 0, marginBottom: 32, fontWeight: 400,
      },

      /* Work list */
      workRow: {
        display: "grid",
        gridTemplateColumns: "44px 1fr auto",
        gap: 22, alignItems: "center",
        padding: "20px 0",
        borderTop: `1px solid ${HAIRLINE}`,
      },
      workRowLast: { borderBottom: `1px solid ${HAIRLINE}` },
      workLogo: {
        width: 32, height: 32, borderRadius: 6,
        background: `color-mix(in oklab, ${FG} 10%, ${BG})`,
        border: `1px solid ${HAIRLINE}`,
      },
      workCo: { fontSize: 20, lineHeight: 1.2 },
      workNote: { color: "inherit", opacity: 0.55, fontStyle: "italic", fontSize: "0.72em", marginLeft: 10 },
      workTitle: { fontSize: 16, color: MUTED, fontStyle: "italic", marginTop: 2 },
      workYears: { fontSize: 15, color: MUTED, fontVariantNumeric: "tabular-nums" },

      /* Projects grid */
      projectGrid: {
        display: "grid",
        gridTemplateColumns: "repeat(auto-fit, minmax(260px, 1fr))",
        gap: 18,
      },
      projectCard: {
        border: `1px solid ${HAIRLINE}`,
        borderRadius: 10,
        padding: "22px 22px 20px",
        background: `color-mix(in oklab, ${FG} 3%, ${BG})`,
        display: "flex", flexDirection: "column",
        gap: 8,
        minHeight: 200,
        transition: "transform 200ms ease, box-shadow 200ms ease",
        cursor: "default",
      },
      projectMeta: {
        fontSize: 12, color: MUTED,
        letterSpacing: "0.08em", textTransform: "uppercase",
      },
      projectTitle: {
        fontSize: 22, letterSpacing: "-0.01em",
        margin: 0, lineHeight: 1.2,
      },
      projectBlurb: {
        fontSize: 15, color: FG, opacity: 0.78,
        margin: 0, marginTop: "auto",
      },

      /* Contact section */
      contactWrap: {
        display: "flex", flexDirection: "column", gap: 16,
        maxWidth: 560,
      },
      contactHeading: {
        fontSize: 32, letterSpacing: "-0.015em",
        margin: 0, fontWeight: 400,
      },
      contactCopy: {
        fontSize: 17, color: MUTED, fontStyle: "italic",
        margin: 0, lineHeight: 1.5,
      },
      contactLinks: {
        marginTop: 8,
        display: "flex", flexDirection: "column", gap: 10,
        fontSize: 18,
      },
      contactLink: {
        color: FG, textDecoration: "none",
        borderBottom: `1px solid ${HAIRLINE}`,
        padding: "10px 0",
        display: "flex", justifyContent: "space-between", alignItems: "baseline",
      },
      contactArrow: { color: MUTED, fontSize: 14 },

      footer: {
        maxWidth: 880, margin: "0 auto",
        padding: "0 32px 56px",
        boxSizing: "border-box",
        fontSize: 13, color: MUTED,
        letterSpacing: "0.06em",
      },
    };
  };

  /* ----------------------------------------------------------------------- */
  /* Chat hero — the headline                                                */
  /* ----------------------------------------------------------------------- */

  function ChatHero({ S, t }) {
    const [draft, setDraft] = useState("");
    const { messages, pending, error, send } = useChat();
    const threadRef = useRef(null);

    useEffect(() => {
      if (threadRef.current) threadRef.current.scrollTop = threadRef.current.scrollHeight;
    }, [messages, pending]);

    const onSubmit = (e) => {
      e.preventDefault();
      if (!draft.trim()) return;
      send(draft);
      setDraft("");
    };

    const onChip = (prompt) => {
      if (pending) return;
      send(prompt);
    };

    return (
      <section style={S.hero}>
        <div style={{ flex: messages.length === 0 && !pending ? 1 : 0, transition: "flex 300ms ease" }} />
        <div style={S.heroIntro}>
          <div style={S.nameRow}>
            <div style={S.avatarWrap}>
              <img src="photo.jpg" alt="Lucas Rollo" style={S.avatar} />
            </div>
            <h1 style={S.heroName}>{SITE.name}</h1>
          </div>
          <p style={S.heroTagline}>{t.tagline}</p>
        </div>

        <div style={S.chatThread} ref={threadRef}>
          {messages.length === 0 && !pending && (
            <div style={S.chatEmpty}>
              Ask the bot what you'd ask me. It's read my notes.
            </div>
          )}
          {messages.map((m, i) => (
            <div key={i} style={m.role === "user" ? S.chatBubbleUser : S.chatBubbleBot}>
              {m.role === "assistant" ? renderMarkdown(m.content) : m.content}
            </div>
          ))}
          {pending && <div style={S.chatThinking}>thinking…</div>}
          {error && <div style={S.chatError}>{error}</div>}
        </div>

        <form style={S.chatInputWrap} onSubmit={onSubmit}>
          <textarea
            style={S.chatInput}
            value={draft}
            rows={1}
            onChange={(e) => setDraft(e.target.value)}
            onKeyDown={(e) => {
              // Plain Enter submits; Shift+Enter inserts a newline.
              // Ctrl/Cmd+Enter never submits (avoids accidental sends).
              if (e.key === "Enter") {
                if (e.shiftKey) return; // let the textarea insert a newline
                e.preventDefault();
                if (!e.ctrlKey && !e.metaKey) onSubmit(e);
              }
            }}
            placeholder="Ask anything about Lucas…"
            disabled={pending}
            aria-label="Ask anything"
          />
          <button
            type="submit"
            style={{ ...S.chatSend, opacity: pending || !draft.trim() ? 0.5 : 1 }}
            disabled={pending || !draft.trim()}
            aria-label="Send"
          >→</button>
        </form>

        <div style={S.promptsRow}>
          {SUGGESTED.map((p) => (
            <button
              key={p}
              style={S.promptChip}
              onClick={() => onChip(p)}
              disabled={pending}
            >{p}</button>
          ))}
        </div>

        <div style={S.scrollHint}>
          <span>or scroll</span>
          <span style={{ width: 28, height: 1, background: "currentColor", opacity: 0.4 }} />
          <span>Work · Projects · Contact</span>
        </div>
      </section>
    );
  }

  /* ----------------------------------------------------------------------- */
  /* Work / Projects / Contact sections                                      */
  /* ----------------------------------------------------------------------- */

  const COMPANY_LOGOS = {
    "Moveworks":        "https://www.google.com/s2/favicons?domain=moveworks.com&sz=64",
    "Qualcomm":         "https://www.google.com/s2/favicons?domain=qualcomm.com&sz=64",
  };

  function CompanyLogo({ company, S }) {
    const [failed, setFailed] = useState(false);
    const src = COMPANY_LOGOS[company];
    if (!src || failed) return <div style={S.workLogo} />;
    return (
      <img
        src={src}
        alt={company}
        style={{ ...S.workLogo, objectFit: "contain", padding: 2 }}
        onError={() => setFailed(true)}
      />
    );
  }

  function WorkSection({ S }) {
    return (
      <section id="work" style={S.section}>
        <div style={S.sectionLabel}>01 — Work</div>
        <h2 style={S.sectionHeading}>Where I've been</h2>
        <div>
          {SITE.workHistory.map((r, i) => (
            <div
              key={i}
              style={{
                ...S.workRow,
                ...(i === SITE.workHistory.length - 1 ? S.workRowLast : null),
              }}
            >
              <CompanyLogo company={r.company} S={S} />
              <div>
                <div style={S.workCo}>
                  {r.company}
                  {r.note && <span style={S.workNote}>({r.note})</span>}
                </div>
                <div style={S.workTitle}>{r.title}</div>
              </div>
              <div style={S.workYears}>{r.years}</div>
            </div>
          ))}
        </div>
      </section>
    );
  }

  function ProjectsSection({ S }) {
    return (
      <section id="projects" style={S.section}>
        <div style={S.sectionLabel}>02 — Projects</div>
        <h2 style={S.sectionHeading}>Things I've shipped</h2>
        <div style={S.projectGrid}>
          {(SITE.projects || []).map((p) => (
            <article key={p.slug} style={S.projectCard}>
              <div style={S.projectMeta}>{p.year} · {p.role}</div>
              <h3 style={S.projectTitle}>{p.title}</h3>
              <p style={S.projectBlurb}>{p.blurb}</p>
            </article>
          ))}
        </div>
      </section>
    );
  }

  function ContactSection({ S }) {
    return (
      <section id="contact" style={S.sectionLast}>
        <div style={S.sectionLabel}>03 — Contact</div>
        <div style={S.contactWrap}>
          <h2 style={S.contactHeading}>Say hi.</h2>
          <p style={S.contactCopy}>
            Open to the right next thing. Recruiters, founders, friends — all welcome.
            The bot upstairs will answer most things; for the rest, here I am.
          </p>
          <div style={S.contactLinks}>
            <a style={S.contactLink} href={SITE.contact.linkedin} target="_blank" rel="noopener noreferrer">
              <span>LinkedIn</span><span style={S.contactArrow}>↗</span>
            </a>
            <a style={S.contactLink} href={`mailto:${SITE.contact.email}`}>
              <span>{SITE.contact.email}</span><span style={S.contactArrow}>↗</span>
            </a>
          </div>
        </div>
      </section>
    );
  }

  /* ----------------------------------------------------------------------- */
  /* ----------------------------------------------------------------------- */
  /* Tweaks panel                                                            */
  /* ----------------------------------------------------------------------- */

  function ChatHomeTweaks({ t, setTweak }) {
    return (
      <TweaksPanel title="Tweaks">
        <TweakSection label="Look">
          <TweakColor
            label="Palette"
            value={t.palette}
            options={PALETTES}
            onChange={(v) => setTweak("palette", v)}
          />
          <TweakSelect
            label="Font"
            value={t.font}
            options={FONT_OPTIONS}
            onChange={(v) => setTweak("font", v)}
          />
        </TweakSection>

        <TweakSection label="Hero">
          <TweakSlider
            label="Name size"
            value={t.nameSize}
            min={40} max={96} step={2} unit="px"
            onChange={(v) => setTweak("nameSize", v)}
          />
          <TweakText
            label="Tagline"
            value={t.tagline}
            placeholder="A line about you"
            onChange={(v) => setTweak("tagline", v)}
          />
        </TweakSection>
      </TweaksPanel>
    );
  }

  /* ----------------------------------------------------------------------- */

  function ChatHomeVariant() {
    const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
    const S = buildStyles(t);

    return (
      <div style={S.root}>
        <ChatHero S={S} t={t} />
        <WorkSection S={S} />
        <ProjectsSection S={S} />
        <ContactSection S={S} />
        <ChatHomeTweaks t={t} setTweak={setTweak} />
      </div>
    );
  }

  window.ChatHomeVariant = ChatHomeVariant;
})();
