/* Reflections.jsx — five 100-word mini reflections + one 500-word major.
   Copy is placeholder in Neel's voice — replace with real writing. */

const MINI_REFLECTIONS = [
  { n: "01", topic: "Editing, Leadership, and Team Building",
    body: "I believe I was able to improve my leadership skills a lot in InFocus this year. I realized that sometimes leading a class that's not fully dedicated is hard. There will be some students that unfortunately will not try their hardest to make the best packages and to pay attention and there is nothing you can do about it. I learned that the best use of time is focusing on the ones who need help but are putting in the effort, because if you help someone who is trying, they could end up becoming great reporters and therefore we could have a larger pool of dedicated and skilled students." },
  { n: "02", topic: "Writing and Reporting",
    body: "In InFocus, I believe I have improved my writing skills, and especially my reporting skills. I learned a lot of new scriptwriting techniques over the year which greatly helped my Airport Day package and my iPhone 17 package. I learned that scriptwriting is a very useful tool as you can transcribe the interviews you had in the editor, paste it into a google doc and then cut down on those interviews using the transcription. This, then allows you to easily visualize the story of the interviews which made it much easier to write my VO script, and demonstrated how the story could flow better." },
  { n: "03", topic: "Broadcast Journalism",
    body: "In InFocus, a broadcast journalism program, I improved significantly this semester on the broadcast. I improved my stories more by adding NAT sound clips at the start then transitioning to my VO or standup. I also learned to separate my interview clips and other interview clips with more VO- as the VO is supposed to tell the obvious facts, while the interviews should tell stories that you could not tell yourself. Additionally, I believe we improved the show slightly this year by adding banter that flows better, as well as doing anchor training. Overall, InFocus as a broadcast publication in terms of quality has increased this year." },
  { n: "04", topic: "Law, Ethics, and News Literacy",
    body: "In InFocus, I have been constantly improving my ethics and news literacy through journalism. As always, I have always tried to stay up to date with the news, I continue to read the news daily as well as Ground News which separates news biases. I try to read it multiple times per day, and I also read a variety of morning financial newsletters and podcasts, which is where I get some of my news ideas from. I have maintained the same ethics standards by being polite to my interviewees, respecting their boundaries and being respectful to everyone I meet." },
  { n: "05", topic: "Commitment to Diversity",
    body: "I believe I have improved my commitment to diversity in InFocus. I have always maintained a policy on trying to balance genders, if possible, within my packages. I attempted that with the Palo Alto Airport Day package but was unable to do so because of the lack of female pilots at the event. Additionally, as producers we try to encourage the students to include more diverse aspects- for example, a lot of packages where students interviewed other students usually contained one single grade and therefore, a piece of advice that we usually give is to interview multiple students across grade levels." },
];

const MAJOR_REFLECTION = {
  topic: "Major Reflection",
  read: "4 min read · protected",
  protected: true,
};

const MAJOR_ACCESS_KEY = "neel-major-reflection-access";

async function fetchMajorReflection({ password, token } = {}) {
  const headers = { "Content-Type": "application/json" };
  if (token) headers.Authorization = `Bearer ${token}`;

  const response = await fetch("/api/major-reflection", {
    method: "POST",
    headers,
    body: JSON.stringify(password ? { password } : {}),
  });
  const data = await response.json().catch(() => ({}));
  if (!response.ok) throw new Error(data.error || "Unable to unlock reflection");
  return data;
}

function readSavedMajorAccess() {
  try {
    const saved = JSON.parse(localStorage.getItem(MAJOR_ACCESS_KEY));
    if (!saved || !saved.token || !saved.expiresAt || saved.expiresAt <= Date.now()) {
      localStorage.removeItem(MAJOR_ACCESS_KEY);
      return null;
    }
    return saved;
  } catch {
    localStorage.removeItem(MAJOR_ACCESS_KEY);
    return null;
  }
}

function saveMajorAccess({ token, expiresAt }) {
  localStorage.setItem(MAJOR_ACCESS_KEY, JSON.stringify({ token, expiresAt }));
}

function Reflections({ onRead }) {
  const [gate, setGate] = React.useState({ open: false, password: "", error: "", loading: false });

  const openMajorReflection = async () => {
    const saved = readSavedMajorAccess();
    if (!saved) {
      setGate({ open: true, password: "", error: "", loading: false });
      return;
    }

    try {
      const data = await fetchMajorReflection({ token: saved.token });
      saveMajorAccess(data);
      onRead(data.reflection);
    } catch {
      localStorage.removeItem(MAJOR_ACCESS_KEY);
      setGate({ open: true, password: "", error: "", loading: false });
    }
  };

  const submitMajorPassword = async (e) => {
    e.preventDefault();
    setGate((g) => ({ ...g, error: "", loading: true }));

    try {
      const data = await fetchMajorReflection({ password: gate.password });
      saveMajorAccess(data);
      setGate({ open: false, password: "", error: "", loading: false });
      onRead(data.reflection);
    } catch (error) {
      setGate((g) => ({ ...g, error: error.message, loading: false }));
    }
  };

  return (
    <div id="reflections" style={{ borderTop: "1px solid var(--border)" }}>
      <Section style={{ paddingTop: 96, paddingBottom: 96 }}>
        <Kicker>[ 04 ] In my own words</Kicker>
        <h2 className="h1" style={{ margin: "14px 0 8px" }}>Reflections</h2>
        <p className="body" style={{ maxWidth: 540, marginBottom: 40 }}>Five mini reflections on different categories and one major reflection on the entire year</p>

        {/* Mini grid — shared-hairline bordered cells */}
        <div className="reflection-grid" style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 1, background: "var(--border)", border: "1px solid var(--border)", marginBottom: 24 }}>
          {MINI_REFLECTIONS.map((r) => <MiniCard key={r.n} r={r} onRead={onRead} />)}
        </div>

        <MajorCard onRead={openMajorReflection} />
      </Section>
      {gate.open && (
        <MajorPasswordDialog
          gate={gate}
          onClose={() => setGate({ open: false, password: "", error: "", loading: false })}
          onChange={(password) => setGate((g) => ({ ...g, password }))}
          onSubmit={submitMajorPassword}
        />
      )}
    </div>
  );
}

function MiniCard({ r, onRead }) {
  const [h, setH] = React.useState(false);
  return (
    <article className="reflection-card" onClick={() => onRead({ ...r, mini: true })} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      style={{ background: h ? "var(--surface-hover)" : "var(--bg)", padding: 28, cursor: "pointer", transition: "background var(--dur) var(--ease)", display: "flex", flexDirection: "column", minHeight: 240 }}>
      <Kicker style={{ color: h ? "var(--blue-bright)" : "var(--fg-3)" }}>R/{r.n}</Kicker>
      <h3 style={{ fontFamily: "var(--font-sans)", fontWeight: 500, fontSize: 20, color: "var(--fg)", margin: "14px 0 12px", lineHeight: 1.2 }}>{r.topic}</h3>
      <p style={{ fontFamily: "var(--font-sans)", fontSize: 14, lineHeight: 1.6, color: "var(--fg-3)", margin: "0 0 20px", display: "-webkit-box", WebkitLineClamp: 3, WebkitBoxOrient: "vertical", overflow: "hidden" }}>{r.body}</p>
      <span style={{ marginTop: "auto", display: "inline-flex", alignItems: "center", gap: 7, fontFamily: "var(--font-mono)", fontSize: 12, letterSpacing: "0.08em", textTransform: "uppercase", color: h ? "var(--fg)" : "var(--fg-3)", transition: "color var(--dur) var(--ease)" }}>
        Read <Icon name="arrow-right" size={14} />
      </span>
    </article>
  );
}

function MajorCard({ onRead }) {
  const [h, setH] = React.useState(false);
  return (
    <article className="major-card" onClick={onRead} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      style={{ border: `1px solid ${h ? "var(--border-strong)" : "var(--border)"}`, background: h ? "var(--surface-1)" : "transparent", padding: "40px 36px", cursor: "pointer", transition: "all var(--dur) var(--ease)", display: "grid", gridTemplateColumns: "1fr 1fr", gap: 40, alignItems: "center" }}>
      <div>
        <Kicker blue>Major reflection</Kicker>
        <h3 style={{ fontFamily: "var(--font-sans)", fontWeight: 500, fontSize: 30, color: "var(--fg)", margin: "16px 0 0", lineHeight: 1.1, maxWidth: 420, letterSpacing: "-.01em" }}>{MAJOR_REFLECTION.topic}</h3>
      </div>
      <div>
        <p style={{ fontFamily: "var(--font-sans)", fontSize: 15, lineHeight: 1.6, color: "var(--fg-2)", margin: "0 0 24px", maxWidth: 420 }}>A 500 word major reflection where I reflect on the performance of the InFocus team in the 2025-2026 school year.</p>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 16 }}>
          <Button variant="ghost" iconRight="arrow-up-right">Read the essay</Button>
          <span className="timecode" style={{ color: "var(--fg-4)" }}>{MAJOR_REFLECTION.read}</span>
        </span>
      </div>
    </article>
  );
}

function MajorPasswordDialog({ gate, onClose, onChange, onSubmit }) {
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 120, background: "rgba(15,17,20,0.88)", display: "grid", placeItems: "center", padding: 20, animation: "neelFade var(--dur) var(--ease)" }}>
      <form onSubmit={onSubmit} onClick={(e) => e.stopPropagation()} style={{ width: "min(100%, 430px)", background: "var(--bg)", border: "1px solid var(--border-strong)", padding: 28 }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 20, marginBottom: 22 }}>
          <Kicker blue>Protected essay</Kicker>
          <button type="button" onClick={onClose} aria-label="Close password prompt" style={{ width: 36, height: 36, display: "grid", placeItems: "center", background: "transparent", border: "1px solid var(--border)", color: "var(--fg-2)", cursor: "pointer" }}>
            <Icon name="x" size={15} />
          </button>
        </div>
        <h3 style={{ fontFamily: "var(--font-sans)", fontWeight: 500, fontSize: 28, color: "var(--fg)", margin: "0 0 12px", lineHeight: 1.1 }}>Major Reflection</h3>
        <p style={{ fontFamily: "var(--font-sans)", fontSize: 14.5, lineHeight: 1.6, color: "var(--fg-3)", margin: "0 0 22px" }}>Enter the password to unlock this reflection. Access will be remembered for 7 days on this device.</p>
        <label className="label" htmlFor="major-password" style={{ display: "block", color: "var(--fg-3)", marginBottom: 8 }}>PASSWORD</label>
        <input
          id="major-password"
          type="password"
          value={gate.password}
          onChange={(e) => onChange(e.target.value)}
          autoFocus
          style={{ width: "100%", boxSizing: "border-box", background: "var(--surface-1)", border: "1px solid var(--border-strong)", color: "var(--fg)", fontFamily: "var(--font-sans)", fontSize: 17, padding: "13px 14px", outline: "none", borderRadius: 0 }}
        />
        {gate.error && <p style={{ color: "var(--blue-bright)", fontFamily: "var(--font-mono)", fontSize: 12, letterSpacing: "0.04em", textTransform: "uppercase", margin: "12px 0 0" }}>{gate.error}</p>}
        <div style={{ display: "flex", justifyContent: "flex-end", gap: 12, marginTop: 24 }}>
          <button type="button" onClick={onClose} style={{ appearance: "none", WebkitAppearance: "none", outline: "none", display: "inline-flex", alignItems: "center", gap: 9, fontFamily: "var(--font-mono)", fontWeight: 400, fontSize: 14, letterSpacing: "0.10em", textTransform: "uppercase", borderRadius: 0, padding: "13px 22px", cursor: "pointer", border: "1px solid var(--border-strong)", transition: "all var(--dur) var(--ease)", background: "transparent", color: "var(--fg)" }}>Cancel</button>
          <button type="submit" disabled={gate.loading || !gate.password.trim()} style={{ appearance: "none", WebkitAppearance: "none", outline: "none", display: "inline-flex", alignItems: "center", gap: 9, fontFamily: "var(--font-mono)", fontWeight: 400, fontSize: 14, letterSpacing: "0.10em", textTransform: "uppercase", borderRadius: 0, padding: "13px 22px", cursor: gate.loading || !gate.password.trim() ? "not-allowed" : "pointer", border: "1px solid transparent", transition: "all var(--dur) var(--ease)", background: gate.loading || !gate.password.trim() ? "rgba(255,255,255,0.42)" : "#ffffff", color: "var(--on-white)" }}>
            <Icon name="lock-keyhole" size={16} /> {gate.loading ? "Unlocking" : "Unlock"}
          </button>
        </div>
      </form>
    </div>
  );
}

Object.assign(window, { Reflections, MINI_REFLECTIONS, MAJOR_REFLECTION });
