/* ============================================================
   Screen: Document Hub + Ask-AI
   ============================================================ */
(function () {
  const DB = window.DB;
  const TODAY = "2026-06-04";
  const days = (a, b) => Math.round((new Date(b) - new Date(a)) / 86400000);
  const CAT_ICON = { "Policy": "compliance", "Handbook": "docs", "Course Outline": "coursework", "Subject Guide": "doc", "Mark Scheme": "progress" };
  const CATS = ["All", "Policy", "Handbook", "Course Outline", "Subject Guide", "Mark Scheme"];

  function reviewStatus(date) {
    const d = days(TODAY, date);
    if (d < 0) return { tone: "crit", label: t("Review overdue") };
    if (d <= 45) return { tone: "watch", label: t("Due") + " " + date.slice(5) };
    return { tone: "ok", label: t("Reviewed to") + " " + date.slice(0, 4) };
  }
  function canAccess(doc, role) {
    if (doc.roles === "all") return true;
    if (role === "director") return doc.roles.includes("director");
    return doc.roles.includes("teacher");
  }

  // English source; translated at render time so they follow the language toggle
  const SUGGESTED = [
    "What is the late-submission penalty?",
    "Summarise the attendance policy",
    "Where are the current IB compliance gaps?",
    "Find the academic-integrity policy",
  ];

  function DocCard({ doc, role, onAsk }) {
    const ok = canAccess(doc, role);
    const rev = reviewStatus(doc.nextReview);
    const owner = DB.teacher(doc.owner);
    return (
      <div className={"doc-card" + (ok ? "" : " locked")}>
        <div className="doc-top">
          <span className="doc-ic"><Icon name={CAT_ICON[doc.cat]} size={17} /></span>
          <span className="eyebrow">{t(doc.cat)}</span>
          {!ok ? <span className="doc-lock"><Icon name="compliance" size={13} /></span> : <span className="mono faint" style={{ marginLeft: "auto", fontSize: 10.5 }}>v{doc.v}</span>}
        </div>
        <div className="doc-title">{doc.title}</div>
        {ok ? (
          <React.Fragment>
            <div className="row" style={{ gap: 7, marginTop: 10 }}>
              <Avatar name={owner.name} color={owner.avatar} size={18} />
              <span className="muted" style={{ fontSize: 11 }}>{owner.name}</span>
              <span className="mono faint" style={{ fontSize: 10, marginLeft: "auto" }}>upd {doc.updated.slice(2)}</span>
            </div>
            <div className="doc-foot">
              <span className={"rev-chip " + rev.tone}><span className="dot"></span>{rev.label}</span>
              <button className="doc-ask" onClick={() => onAsk(t("Summarise the") + " " + doc.title)} title={t("Ask AI about this document")}><Icon name="spark" size={13} /></button>
            </div>
          </React.Fragment>
        ) : (
          <div className="doc-restricted">
            <span style={{ fontSize: 11.5, color: "var(--muted)" }}>{t("Restricted — not available to your role.")}</span>
          </div>
        )}
      </div>
    );
  }

  function Documents({ role, navigate }) {
    const [cat, setCat] = React.useState("All");
    const [q, setQ] = React.useState("");
    const [question, setQuestion] = React.useState("");
    const [answer, setAnswer] = React.useState(null);
    const [thinking, setThinking] = React.useState(false);
    const [uploadOpen, setUploadOpen] = React.useState(false);

    const docs = DB.DOCUMENTS.filter((d) => (cat === "All" || d.cat === cat) && (!q || d.title.toLowerCase().includes(q.toLowerCase())));

    const ask = (text) => {
      if (!text.trim()) return;
      setQuestion(text); setAnswer(null); setThinking(true);
      setTimeout(() => { setThinking(false); setAnswer(window.AI.respond(text)); }, 700);
    };
    const docByTitle = (name) => DB.DOCUMENTS.find((d) => name.toLowerCase().includes(d.title.toLowerCase().slice(0, 14)));

    return (
      <div className="screen">
        <div className="between" style={{ marginBottom: 16 }}>
          <div>
            <h2 style={{ fontSize: 19 }}>{t("Document Hub")}</h2>
            <p className="muted" style={{ fontSize: 13, marginTop: 4 }}>{t("The school's policies, handbooks and guides — searchable, versioned, and answerable by AI.")}</p>
          </div>
          <button className="btn btn-sm btn-primary" onClick={() => setUploadOpen(true)}><Icon name="plus" size={14} />{t("Upload")}</button>
        </div>

        {/* Ask-AI hero */}
        <div className="ask-hero">
          <div className="ask-head">
            <span className="asst-mark"><Icon name="spark" size={16} /></span>
            <div>
              <h3 style={{ fontSize: 15 }}>{t("Ask the document library")}</h3>
              <p className="muted" style={{ fontSize: 12, marginTop: 2 }}>{t("Answers are drawn from the school's own documents, with citations — and respect what your role can access.")}</p>
            </div>
            <span className="badge accent" style={{ marginLeft: "auto" }}><Icon name="staff" size={11} />{role === "director" ? t("Director access") : t("Teacher access")}</span>
          </div>
          <div className="ask-input">
            <Icon name="search" size={17} />
            <input value={question} onChange={(e) => setQuestion(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") ask(question); }}
              placeholder={t("e.g. What happens if an IA is submitted two days late?")} />
            <button className="btn btn-primary btn-sm" onClick={() => ask(question)} disabled={!question.trim()}>{t("Ask")}<Icon name="arrowR" size={13} /></button>
          </div>
          {!answer && !thinking ? (
            <div className="row wrap" style={{ gap: 7, marginTop: 12 }}>
              {SUGGESTED.map((s) => <button key={s} className="asst-chip" onClick={() => ask(s)}>{t(s)}</button>)}
            </div>
          ) : null}
          {thinking ? <div className="ask-answer"><span className="asst-typing"><i></i><i></i><i></i></span></div> : null}
          {answer ? (
            <div className="ask-answer">
              <div className="ask-q"><Icon name="search" size={13} />{question}</div>
              <p style={{ fontSize: 13.5, lineHeight: 1.6, whiteSpace: "pre-wrap" }}>{answer.text}</p>
              {answer.sources && answer.sources.length ? (
                <div className="ask-sources">
                  <span className="eyebrow">{t("Cited from")}</span>
                  {answer.sources.map((s, i) => {
                    const d = docByTitle(s.doc);
                    return (
                      <button key={i} className="src-chip" onClick={() => { if (d) { setCat("All"); setQ(d.title); } }}>
                        <Icon name="doc" size={12} /><b>{s.doc}</b><span className="faint">· {s.ref}</span><span className="mono faint">{s.v}</span>
                      </button>
                    );
                  })}
                </div>
              ) : null}
              <div className="ask-foot">
                <span className="mono faint" style={{ fontSize: 10.5 }}>{t("AI draft · verify against the source before acting")}</span>
                <button className="btn btn-sm btn-ghost" onClick={() => { setAnswer(null); setQuestion(""); }}>{t("Clear")}</button>
              </div>
            </div>
          ) : null}
        </div>

        {/* library */}
        <div className="toolbar" style={{ margin: "22px 0 14px" }}>
          <div className="row wrap" style={{ gap: 6 }}>
            {CATS.map((c) => <button key={c} className={"chip-filter" + (cat === c ? " on" : "")} onClick={() => setCat(c)}>{t(c)}</button>)}
          </div>
          <div className="tb-input" style={{ marginLeft: "auto" }}>
            <Icon name="search" size={15} />
            <input value={q} onChange={(e) => setQ(e.target.value)} placeholder={t("Search documents…")} />
          </div>
        </div>

        <div className="doc-grid">
          {docs.map((d) => <DocCard key={d.id} doc={d} role={role} onAsk={ask} />)}
        </div>
        {!docs.length ? <div className="cmd-empty muted" style={{ padding: 40 }}>{t("No documents match.")}</div> : null}

        {uploadOpen ? (
          <FormModal title={t("Upload a document")} subtitle={t("New documents are versioned and indexed for the Ask-AI library.")}
            fields={[
              { k: "title", label: t("Document title"), ph: t("e.g. Assessment Policy"), required: true },
              { k: "cat", label: t("Category"), type: "select", options: [t("Policy"), t("Handbook"), t("Course Outline"), t("Subject Guide"), t("Mark Scheme")] },
              { k: "review", label: t("Next review date"), ph: "YYYY-MM-DD" },
              { k: "access", label: t("Access"), type: "select", options: [t("All staff"), t("Leadership only"), t("Counsellor & Director"), t("Teachers & Academic")] },
            ]}
            submitLabel={t("Upload")} submitIcon="download"
            onClose={() => setUploadOpen(false)}
            onSubmit={(v) => { setUploadOpen(false); window.toast((v.title || t("Document")) + " " + t("uploaded · indexed for AI")); }} />
        ) : null}
      </div>
    );
  }

  window.SCREENS = window.SCREENS || {};
  window.SCREENS.docs = Documents;
})();
