// Reuseables //

// SectionWrap is a wrapper for each section
function SectionWrap({ id, title, children }) {
  return (
    <section id={id} data-screen-label={title} style={{ scrollMarginTop: 30, marginTop: 60 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 18 }}>
        <span className="dimmer" style={{ fontSize: 11, letterSpacing: 1.5, textTransform: "uppercase" }}>{title}</span>
        <span style={{ flex: 1, height: 1, background: "linear-gradient(to right, var(--line-2), transparent)" }} />
      </div>
      {children}
    </section>
  );
}

// Card is a card.. yeah.
function Card({ children, glow = false }) {
  return (
    <div style={{
      background: "color-mix(in oklch, var(--bg-2) 80%, transparent)",
      border: "1px solid var(--line)",
      borderRadius: 6,
      padding: "18px 20px",
      boxShadow: glow ? "0 0 40px -10px color-mix(in oklch, var(--accent) 25%, transparent)" : "none",
    }}>{children}</div>
  );
}

// Main Sections //

// UptimeInline counts uptime since page was loaded in.
function UptimeInline() {
  const [t0] = React.useState(() => Date.now());
  const now = useNow(1000);
  const s = Math.floor((now.getTime() - t0) / 1000);
  const fmt = `${String(Math.floor(s / 60)).padStart(2, "0")}:${String(s % 60).padStart(2, "0")}`;
  return <span className="accent">{fmt}</span>
}

// HetoBtn to jump to section in the page
function HeroBtn({ children, onClick, primary = false }) {
  const [hover, setHover] = React.useState(false);
  return (
    <button onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        appearance: "none", cursor: "pointer",
        background: primary
          ? (hover ? "color-mix(in oklch, var(--accent) 30%, transparent)" : "color-mix(in oklch, var(--accent) 18%, transparent)")
          : (hover ? "var(--bg-3)" : "transparent"),
        color: primary ? "var(--accent)" : "var(--text)",
        border: `1px solid ${primary ? "color-mix(in oklch, var(--accent) 50%, transparent)" : "var(--line-2)"}`,
        padding: "6px 12px",
        borderRadius: 4,
        fontFamily: "var(--mono)",
        fontSize: 12,
        transition: "all .12s",
      }}>
      {children}
    </button>
  );
}

// Hero section
function Hero({ onJump }) {
  const [phase, setPhase] = React.useState(0);

  const l1 = useTypewriter(HERO.line1, { speed: 38, start: phase >= 1, onDone: () => setPhase((p) => Math.max(p, 2)) });
  const l2 = useTypewriter(HERO.line2, { speed: 20, start: phase >= 2, onDone: () => setPhase((p) => Math.max(p, 3)) });
  const l3 = useTypewriter(HERO.line3, { speed: 18, start: phase >= 3, onDone: () => setPhase((p) => Math.max(p, 4)) });

  React.useEffect(() => {
    const id = setTimeout(() => setPhase(1), 400);
    return () => clearTimeout(id);
  }, []);

  return (
    <TerminalWindow title="clicky@keys: ~">
      <div style={{ marginBottom: 18, overflow: "hidden" }}>
        <AsciiBanner />
      </div>

      <div style={{ marginBottom: 14, color: "var(--text-dim)", fontSize: 13 }}>
        <span className="accent">Arch Linux</span> · last login: today, on tty1 · uptime <UptimeInline />
      </div>

      <div style={{ borderTop: "1px dashed var(--line)", paddingTop: 14, lineHeight: 1.7 }}>
        <div>
          <Prompt />
          <span className="accent">{l1}</span>
          {phase >= 1 && phase < 2 && <Cursor />}
        </div>
        {phase >= 2 && (
          <div style={{ marginTop: 4 }}>
            <Prompt /><span>{l2}</span>
            {phase < 3 && <Cursor />}
          </div>
        )}
        {phase >= 3 && (
          <div style={{ marginTop: 4 }}>
            <Prompt /><span>{l3}</span>
            {phase < 4 && <Cursor />}
          </div>
        )}

        {/* Buttons appear after all 3 lines finish */}
        {phase >= 4 && (
          <div style={{ marginTop: 16, display: "flex", flexWrap: "wrap", gap: 8 }}>
            {/* ← customize these labels and targets to your liking */}
            <HeroBtn onClick={() => onJump("projects")}>cd projects/</HeroBtn>
            <HeroBtn onClick={() => onJump("now")}>cat .now</HeroBtn>
            {/* <HeroBtn onClick={() => onJump("resume")}>git log --resume</HeroBtn> */}
            <HeroBtn onClick={() => onJump("contact")} primary>./say-hi</HeroBtn>
            <HeroBtn onClick={() => onJump("shell")}>bash --interactive</HeroBtn>
          </div>
        )}
      </div>
    </TerminalWindow>
  );
}

// AboutSection displays information about me.
function AboutSection() {
  return (
    <SectionWrap id="about" title="01 / about">
      <ShellLine cmd="cat about.md">
        <Card>
          <div style={{ display: "grid", gap: 14 }}>

            <p style={{ margin: 0 }}>
              {/* ← your bio here */}
              hello there, i'm a CS undergrad who is one year away from finishing. <br></br>
              im not the smartest out there but i try my best to succeed. <br></br>
              i enjoy programming and tinkering with things. research is also something that has recently became an interest of mine. <br></br>
              i have my own home server and will try to self-host as many services as i possible am able to.
            </p>

            <p style={{ margin: 0 }} className="dim">
              {/* ← outside-the-terminal stuff */}
              outside the terminal: baking, watching shows, preparing for capstone, losing to my sleep deprivation.
            </p>

            <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginTop: 4 }}>
              {ABOUT_TAGS.map((t) => (
                <Tag key={t.text} color={t.color}>{t.text}</Tag>
              ))}
            </div>

          </div>
        </Card>
      </ShellLine>
    </SectionWrap>
  );
}

// ProjectSection is for my projects, will show each one and then when i hover on it it shows its description.
function ProjectsSection() {
  const [hover, setHover] = React.useState(null);

  return (
    <SectionWrap id="projects" title="02 / projects">
      <ShellLine cmd="ls -lah ~/projects">
        <Card>
          <div style={{ display: "grid", gap: 2 }}>

            {/* header */}
            <div className="dimmer" style={{
              display: "grid",
              gridTemplateColumns: "80px 100px 1fr 60px 80px",
              gap: 14, fontSize: 11,
              textTransform: "uppercase", letterSpacing: .8,
              borderBottom: "1px solid var(--line)",
              paddingBottom: 6, marginBottom: 4,
            }}>
              <span>perm</span>
              <span>type</span>
              <span>name</span>
              <span>vis</span>
              <span style={{ textAlign: "right" }}>year</span>
            </div>

            {/* project rows */}
            {PROJECTS.map((p, i) => {
              const isHover = hover === i;
              const statusColor = p.status === "active" ? "var(--accent)" : p.status === "paused" ? "var(--warn)" : "var(--text-dimmer)";
              return (
                <div key={p.name}
                  onMouseEnter={() => setHover(i)}
                  onMouseLeave={() => setHover(null)}
                  style={{
                    borderLeft: `2px solid ${isHover ? "var(--accent)" : "transparent"}`,
                    background: isHover ? "color-mix(in oklch, var(--accent) 8%, transparent)" : "transparent",
                    padding: "8px 10px",
                    borderRadius: 3,
                    transition: "all .12s",
                    cursor: "default",
                  }}>

                  {/* main rows */}
                  <div style={{
                    display: "grid",
                    gridTemplateColumns: "80px 100px 1fr 60px 80px",
                    gap: 14, alignItems: "center", fontSize: 13,
                  }}>
                    <span className="dimmer">drwxr-x</span>
                    <span className="warn">{p.type}</span>
                    <span>
                      <span style={{ color: statusColor }}>● </span>
                      <span className="accent" style={{ fontWeight: 500 }}>{p.name}</span>
                      <span className="dim">/</span>
                    </span>
                    <span className="dimmer">{p.private ? "prvt" : "pblc"}</span>
                    <span className="dimmer" style={{ textAlign: "right" }}>{p.year}</span>
                  </div>

                  {/* showing desc of the project "blurb"*/}
                  <div className="dim" style={{
                    fontSize: 12.5,
                    marginTop: 4,
                    maxHeight: isHover ? 60 : 0,
                    overflow: "hidden",
                    transition: "max-height .25s ease-out",
                    lineHeight: 1.5,
                  }}>
                    <span className="dimmer">└─ </span>{p.blurb}
                  </div>

                </div>
              );
            })}

          </div>
        </Card>
      </ShellLine>
    </SectionWrap>
  );
}

// NowSection is what im working on right now (sort of)
function NowSection() {
  return (
    <SectionWrap id="now" title="03 / now">
      <ShellLine cmd="ps aux --sort=-%cpu | head -n 6" speed={35}>
        <Card>
          <div style={{
            display: "grid",
            gridTemplateColumns: "60px 60px 30px 1fr",
            gap: 14, fontSize: 13,
          }}>
            {/* header */}
            <span className="dimmer" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: .8 }}>PID</span>
            <span className="dimmer" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: .8 }}>%CPU</span>
            <span className="dimmer" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: .8 }}>ST</span>
            <span className="dimmer" style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: .8 }}>COMMAND</span>

            {/* rows here */}
            {NOW.map((p) => {
              const stColor = p.state === "R" ? "var(--accent)"
                : p.state === "S" ? "var(--warn)"
                : "var(--text-dimmer)";
              return (
                <React.Fragment key={p.pid}>
                  <span className="dim" style={{ fontVariantNumeric: "tabular-nums" }}>{p.pid}</span>
                  <span style={{ fontVariantNumeric: "tabular-nums" }}>{p.cpu}</span>
                  <span style={{ color: stColor, fontWeight: 700 }}>{p.state}</span>
                  <span style={{ color: p.state === "D" ? "var(--text-dimmer)" : "var(--text)" }}>
                    {p.cmd}
                  </span>
                </React.Fragment>
              );
            })}
          </div>
        </Card>
      </ShellLine>
    </SectionWrap>
  );
}

// ResumeSection is for my... resume. but commented out right now until i add more.
// function ResumeSection() {
//   return (
//     <SectionWrap id="resume" title="04 / resume">
//       <ShellLine cmd="git log --oneline --graph ~/life" speed={35}>
//         <Card>
//           <div>
//             {RESUME.map((r, i) => (
//               <div key={r.hash} style={{
//                 display: "grid",
//                 gridTemplateColumns: "32px 80px 90px 1fr",
//                 gap: 14,
//                 padding: "10px 0",
//                 borderBottom: i < RESUME.length - 1 ? "1px dashed var(--line)" : "none",
//                 position: "relative",
//               }}>
//                 {/* graph dot + line */}
//                 <span style={{ position: "relative" }}>
//                   <span className="accent" style={{ fontSize: 16 }}>{i === 0 ? "*" : "•"}</span>
//                   {i < RESUME.length - 1 && (
//                     <span style={{
//                       position: "absolute", left: 4, top: 22, bottom: -10,
//                       width: 1, background: "var(--line-2)",
//                     }} />
//                   )}
//                 </span>

//                 {/* hash */}
//                 <span className="warn" style={{ fontSize: 12, fontFamily: "var(--mono)" }}>{r.hash}</span>

//                 {/* date */}
//                 <span className="dimmer" style={{ fontSize: 12 }}>{r.date}</span>

//                 {/* content */}
//                 <div>
//                   <div style={{ display: "flex", gap: 8, alignItems: "baseline", flexWrap: "wrap" }}>
//                     <span className="accent" style={{ fontWeight: 500 }}>{r.who}</span>
//                     <Tag color={
//                       r.tag === "award"    ? "var(--warn)"     :
//                       r.tag === "research" ? "#9aa3ff"         :
//                       r.tag === "intern"   ? "var(--accent)"   :
//                       "var(--text-dim)"
//                     }>{r.tag}</Tag>
//                   </div>
//                   <div className="dim" style={{ marginTop: 3, fontSize: 13 }}>{r.role}</div>
//                 </div>
//               </div>
//             ))}
//           </div>

//           <div className="dimmer" style={{ marginTop: 12, fontSize: 11, fontStyle: "italic" }}>
//             HEAD → main · more commits incoming
//           </div>
//         </Card>
//       </ShellLine>
//     </SectionWrap>
//   );
// }

// ContactSection shows some contact info, rn its just github and a fake email till i decide what to do with it.
function ContactSection() {
  const [copied, setCopied] = React.useState(null);

  const copy = (text, label) => {
    navigator.clipboard.writeText(text).then(() => {
      setCopied(label);
      setTimeout(() => setCopied(null), 1800);
    });
  };

  return (
    <SectionWrap id="contact" title="05 / contact">
      <ShellLine cmd="cat ~/.contacts" speed={35}>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
          {CONTACTS.map((c) => (
            <div key={c.label}
              onClick={() => copy(c.who, c.label)}
              style={{
                display: "flex", alignItems: "baseline", gap: 10,
                padding: "8px 12px",
                border: `1px solid ${copied === c.label ? "var(--accent)" : "var(--line)"}`,
                borderRadius: 4,
                background: copied === c.label ? "color-mix(in oklch, var(--accent) 8%, transparent)" : "var(--bg)",
                transition: "all .15s",
                cursor: "pointer",
              }}
              onMouseEnter={(e) => {
                if (copied !== c.label) e.currentTarget.style.borderColor = "color-mix(in oklch, var(--accent) 50%, transparent)";
                e.currentTarget.style.transform = "translateY(-1px)";
              }}
              onMouseLeave={(e) => {
                if (copied !== c.label) e.currentTarget.style.borderColor = "var(--line)";
                e.currentTarget.style.transform = "none";
              }}>
              <span className="dimmer" style={{ fontSize: 11, minWidth: 50 }}>{c.label}</span>
              <span className="warn">{c.proto}://</span>
              <span className="accent" style={{ wordBreak: "break-all" }}>{c.who}</span>
              {copied === c.label && <span className="dimmer" style={{ marginLeft: "auto", fontSize: 10 }}>copied ✓</span>}
            </div>
          ))}
        </div>
      </ShellLine>
    </SectionWrap>
  );
}

// ShellSection is a fun little 'terminal' section where some functioning commands exists.
function ShellSection() {
  const [val, setVal] = React.useState("");
  const [history, setHistory] = React.useState([]);

  const submit = (e) => {
    e.preventDefault();
    const v = val.trim();
    if (!v) return;
    const lc = v.toLowerCase();
    let out = " ";
    if (lc === "whoami") out = "clicky";
    else if (lc === "ls") out = "about/  projects/  now/  resume/  README.md";
    else if (lc === "date") out = new Date().toString();
    else if (lc === "help") out = "available: whoami, ls, date, clear, sudo, cowsay <text>, vim, :q, exit";
    else if (lc === "clear") { setHistory([]); setVal(""); return; }
    else if (lc === "exit") out = "there is no exit.";
    else if (lc === "vim") out = "you opened vim. good luck leaving.";
    else if (lc === ":q") out = "nice try. still here.";
    else if (lc.startsWith("sudo")) out = "[sudo] password for clicky: ******   nice try.";
    else if (lc === "rm -rf /") out = "lol no.";
    else if (lc.startsWith("cowsay ")) out = makeCowsay(v.slice(7));
    else if (lc === "cowsay") out = makeCowsay("moo");
    else out = `command not found: ${v}. try: help`;
    setHistory((h) => [...h, { cmd: v, out }].slice(-6));
    setVal("");
  };

  return (
    <SectionWrap id="shell" title="06 / shell">
      <ShellLine cmd="bash --interactive" speed={35} autoplay>
        <TerminalWindow title="clicky@keys: ~">
          <div style={{ minHeight: 100 }}>
            {history.map((h, i) => (
              <div key={i} style={{ marginBottom: 6 }}>
                <div><Prompt />{h.cmd}</div>
                <div className="dim" style={{ whiteSpace: "pre-wrap" }}>{h.out}</div>
              </div>
            ))}
            <form onSubmit={submit} style={{ display: "flex", alignItems: "center" }}>
              <Prompt />
              <input
                value={val}
                onChange={(e) => setVal(e.target.value)}
                placeholder={history.length ? "" : "type 'help' and hit enter…"}
                style={{
                  flex: 1, background: "transparent",
                  border: 0, outline: 0,
                  color: "var(--text)", fontFamily: "var(--mono)",
                  fontSize: 14, caretColor: "var(--accent)",
                }}
                autoComplete="off" spellCheck="false"
              />
            </form>
          </div>
        </TerminalWindow>
      </ShellLine>
    </SectionWrap>
  );
}

// Exports line
Object.assign(window, { UptimeInline, HeroBtn, Hero, SectionWrap, Card, AboutSection, ProjectsSection, NowSection, ContactSection, ShellSection });