/* dashboard.jsx — document manager / home screen */

function timeAgo(ts) {
  if (!ts) return "";
  const d = Date.now() - new Date(ts).getTime();
  if (d < 60000) return "Just now";
  if (d < 3600000) return Math.floor(d / 60000) + "m ago";
  if (d < 86400000) return Math.floor(d / 3600000) + "h ago";
  if (d < 604800000) return Math.floor(d / 86400000) + "d ago";
  return new Date(ts).toLocaleDateString("en-US", { month: "short", day: "numeric" });
}

function loadAllDocs() {
  try { return JSON.parse(localStorage.getItem("bdr_docs") || "[]"); } catch { return []; }
}
function saveAllDocs(docs) { localStorage.setItem("bdr_docs", JSON.stringify(docs)); }
function loadDocData(id) { try { return JSON.parse(localStorage.getItem("bdr_doc_" + id)); } catch { return null; } }
function saveDocData(id, payload) { localStorage.setItem("bdr_doc_" + id, JSON.stringify(payload)); }

window.timeAgo = timeAgo;
window.loadAllDocs = loadAllDocs;
window.saveAllDocs = saveAllDocs;
window.loadDocData = loadDocData;
window.saveDocData = saveDocData;

function DashDocCard({ doc, onOpen, onDelete, onDuplicate }) {
  const docPayload = React.useMemo(() => loadDocData(doc.id) || {}, [doc.id]);
  const data = docPayload.data || window.SAMPLE_RESUME;
  const design = docPayload.design || { font: "auto", accent: "#1C9BE6" };
  const accent = design.accent || "#1C9BE6";
  const [menuOpen, setMenuOpen] = React.useState(false);

  return (
    <div className="doc-card">
      <div className="doc-thumb" onClick={onOpen}>
        <div className="doc-mini">
          <div style={{ width: 816, background: "#fff", pointerEvents: "none" }}>
            <Resume data={data} template={doc.template || "modern"} accent={accent} design={design} />
          </div>
        </div>
        <div className="doc-thumb-hover">
          <span className="btn btn-grad btn-sm" style={{ pointerEvents: "none" }}>Open →</span>
        </div>
      </div>
      <div className="doc-footer">
        <div className="doc-info" onClick={onOpen}>
          <div className="doc-name">{doc.name || "Untitled Résumé"}</div>
          <div className="doc-meta">
            {(window.TEMPLATES && window.TEMPLATES[doc.template] ? window.TEMPLATES[doc.template].name : "Modern")} · {timeAgo(doc.updatedAt)}
          </div>
        </div>
        <div style={{ position: "relative", flexShrink: 0 }}>
          <button className="icon-btn" onClick={function(e) { e.stopPropagation(); setMenuOpen(function(m) { return !m; }); }} title="More options">
            <Icon name="grip" size={15} />
          </button>
          {menuOpen && (
            <React.Fragment>
              <div style={{ position: "fixed", inset: 0, zIndex: 99 }} onClick={function() { return setMenuOpen(false); }} />
              <div className="doc-ctx-menu">
                <button className="doc-ctx-item" onClick={function() { onOpen(); setMenuOpen(false); }}>
                  <Icon name="eye" size={14} /> Open
                </button>
                <button className="doc-ctx-item" onClick={function() { onDuplicate(); setMenuOpen(false); }}>
                  <Icon name="copy" size={14} /> Duplicate
                </button>
                <div className="ctx-sep" />
                <button className="doc-ctx-item danger" onClick={function() { onDelete(); setMenuOpen(false); }}>
                  <Icon name="trash" size={14} /> Delete
                </button>
              </div>
            </React.Fragment>
          )}
        </div>
      </div>
    </div>
  );
}

function Dashboard({ onOpen, onNew }) {
  const [docs, setDocs] = React.useState(loadAllDocs);
  const [confirmDel, setConfirmDel] = React.useState(null);
  const fileRef = React.useRef(null);

  const handleDelete = function(id) {
    const next = docs.filter(function(d) { return d.id !== id; });
    saveAllDocs(next);
    try { localStorage.removeItem("bdr_doc_" + id); } catch(e) {}
    setDocs(next);
    setConfirmDel(null);
  };

  const handleDuplicate = function(id) {
    const src = docs.find(function(d) { return d.id === id; });
    if (!src) return;
    const newId = Math.random().toString(36).slice(2, 9);
    const srcData = loadDocData(id);
    const newDoc = Object.assign({}, src, { id: newId, name: (src.name || "Résumé") + " (copy)", updatedAt: new Date().toISOString() });
    const next = [newDoc].concat(docs);
    saveAllDocs(next);
    if (srcData) saveDocData(newId, Object.assign({}, srcData, { docName: newDoc.name }));
    setDocs(next);
  };

  const handleImport = function(e) {
    const f = e.target.files && e.target.files[0];
    if (!f) return;
    const reader = new FileReader();
    reader.onload = function(ev) {
      try {
        const payload = JSON.parse(ev.target.result);
        const id = Math.random().toString(36).slice(2, 9);
        const newDoc = {
          id: id,
          name: payload.docName || f.name.replace(/\.json$/, "") || "Imported Résumé",
          template: payload.template || "modern",
          updatedAt: new Date().toISOString(),
        };
        const next = [newDoc].concat(docs);
        saveAllDocs(next);
        saveDocData(id, payload);
        setDocs(next);
        onOpen(id);
      } catch(err) {
        alert("Could not read the file. Make sure it is an exported BDRecruit résumé (.json).");
      }
    };
    reader.readAsText(f);
    e.target.value = "";
  };

  const delDoc = docs.find(function(d) { return d.id === confirmDel; });
  const tplKeys = window.TEMPLATES ? Object.keys(window.TEMPLATES) : [];

  return (
    <div className="dash">
      <div className="dash-topbar">
        <div className="brand">
          <img src="assets/logo.png" alt="BDRecruit" style={{ width: 30, height: 30 }} />
          <span className="wordmark">BD<b style={{ color: "var(--brand-blue)" }}>Recruit</b></span>
          <span className="tag">Resume Studio</span>
        </div>
        <div style={{ flex: 1 }} />
        <button className="btn btn-ghost btn-sm" onClick={function() { fileRef.current && fileRef.current.click(); }}>
          <Icon name="import" size={15} /> Import JSON
        </button>
        <button className="btn btn-grad" onClick={function() { onNew(); }}>
          <Icon name="plus" size={15} /> New Résumé
        </button>
        <input ref={fileRef} type="file" accept=".json" style={{ display: "none" }} onChange={handleImport} />
      </div>

      <div className="dash-body scroll">
        <div className="dash-section">
          <div className="dash-hero">
            <div>
              <h2 className="dash-h2">My Résumés</h2>
              <p className="dash-sub">{docs.length} document{docs.length !== 1 ? "s" : ""} saved locally</p>
            </div>
          </div>

          {docs.length === 0 ? (
            <div className="dash-empty">
              <div className="dash-empty-ico"><Icon name="doc" size={44} /></div>
              <h3>No résumés yet</h3>
              <p>Create your first résumé and land that next role.</p>
              <button className="btn btn-grad" style={{ marginTop: 16 }} onClick={function() { onNew(); }}>
                <Icon name="plus" size={16} /> Create Résumé
              </button>
            </div>
          ) : (
            <div className="doc-grid">
              <div className="doc-card doc-new-card" onClick={function() { onNew(); }}>
                <div className="doc-new-inner">
                  <div className="doc-new-icon"><Icon name="plus" size={32} /></div>
                  <span>New Résumé</span>
                </div>
              </div>
              {docs.map(function(doc) {
                return (
                  <DashDocCard
                    key={doc.id}
                    doc={doc}
                    onOpen={function() { onOpen(doc.id); }}
                    onDelete={function() { setConfirmDel(doc.id); }}
                    onDuplicate={function() { handleDuplicate(doc.id); }}
                  />
                );
              })}
            </div>
          )}
        </div>

        <div className="dash-section dash-templates">
          <h2 className="dash-h2">Start from a template</h2>
          <p className="dash-sub">All templates are ATS-verified — switch any time without losing your content.</p>
          <div className="tpl-starter-grid">
            {tplKeys.map(function(key) {
              const tpl = window.TEMPLATES[key];
              return (
                <button key={key} className="tpl-starter-card" onClick={function() { onNew(key); }}>
                  <div className="tpl-thumb" style={{ height: 180 }}>
                    <div className="mini">
                      <div style={{ width: 816, background: "#fff", pointerEvents: "none" }}>
                        <Resume
                          data={window.SAMPLE_RESUME}
                          template={key}
                          accent={(tpl && tpl.defaultAccent) || "#1C9BE6"}
                          design={{ font: "auto" }}
                        />
                      </div>
                    </div>
                  </div>
                  <div className="tpl-meta" style={{ background: "#fff" }}>
                    <span className="nm">{tpl && tpl.name}</span>
                    <span className="badge">{tpl && tpl.badge}</span>
                    <span className="ats"><Icon name="check" size={11} style={{ verticalAlign: "-1px" }} /> ATS</span>
                  </div>
                </button>
              );
            })}
          </div>
        </div>

        <div className="dash-section">
          <div className="dash-feature-row">
            <div className="dash-feature-card">
              <div className="dfeat-icon" style={{ background: "rgba(28,155,230,.1)", color: "var(--brand-blue)" }}><Icon name="letter" size={22} /></div>
              <h4>Cover Letter</h4>
              <p>Write a tailored cover letter that references your résumé data automatically.</p>
            </div>
            <div className="dash-feature-card">
              <div className="dfeat-icon" style={{ background: "rgba(52,199,127,.1)", color: "var(--brand-green)" }}><Icon name="target" size={22} /></div>
              <h4>Job Match</h4>
              <p>Paste any job description and instantly see which keywords your résumé is missing.</p>
            </div>
            <div className="dash-feature-card">
              <div className="dfeat-icon" style={{ background: "rgba(109,90,224,.1)", color: "#6D5AE0" }}><Icon name="bolt" size={22} /></div>
              <h4>ATS Score</h4>
              <p>Real-time scoring across 7 weighted categories so recruiters and bots both love your résumé.</p>
            </div>
            <div className="dash-feature-card">
              <div className="dfeat-icon" style={{ background: "rgba(224,160,19,.1)", color: "var(--warn)" }}><Icon name="export" size={22} /></div>
              <h4>Smart Export</h4>
              <p>Download a pixel-perfect PDF or a clean ATS-safe plain-text PDF — your choice.</p>
            </div>
          </div>
        </div>
      </div>

      {confirmDel && (
        <div className="modal-back" onClick={function() { setConfirmDel(null); }}>
          <div className="confirm-modal" onClick={function(e) { e.stopPropagation(); }}>
            <h3>Delete "{delDoc ? delDoc.name : "this résumé"}"?</h3>
            <p>This can't be undone. All data for this résumé will be permanently removed.</p>
            <div className="confirm-actions">
              <button className="btn btn-ghost btn-sm" onClick={function() { setConfirmDel(null); }}>Cancel</button>
              <button className="btn btn-sm" style={{ background: "var(--bad)", color: "#fff", border: "none" }}
                onClick={function() { handleDelete(confirmDel); }}>Delete</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

window.Dashboard = Dashboard;
