/* ============================================================
   Company Categories Management — per Proud Workpapers PDF slide 2
   ============================================================
   Admin can edit / add / remove company-category definitions
   (Cat A — PIE, B — progressing, C — large privately-held, D — others).

   Each category drives sampling intensity, EQR triggers, partner-review
   depth, and regulatory reporting under ก.ล.ต. rules.
   ============================================================ */

/* ====== Add / Edit Company Category modal — just Name + Description ======
   Key (A–Z) is derived from the name on create; the short summary is
   derived from the first sentence of the description so existing
   consumers (Project form dropdown labels + helper text) keep working. */
const CompanyCategoryFormModal = ({ initial, existingKeys, onClose, onSave }) => {
  const isEdit = !!initial;
  const [name, setName] = React.useState(initial?.label || "");
  const [desc, setDesc] = React.useState(initial?.desc || "");

  const nameValid = name.trim().length >= 3;
  const descValid = desc.trim().length >= 3;
  const canSave = nameValid && descValid;

  /* Auto-derive a single A–Z key from the display name. Walks the
     alphabet looking for the first letter from the name that isn't
     already taken; falls back to "E" → "Z" sweep. */
  const deriveKey = (n) => {
    const letters = n.toUpperCase().replace(/[^A-Z]/g, "");
    for (const ch of letters) {
      if (!existingKeys.includes(ch)) return ch;
    }
    for (let i = 0; i < 26; i++) {
      const ch = String.fromCharCode(69 + i); // start at "E"
      if (!existingKeys.includes(ch)) return ch;
    }
    return "Z";
  };

  /* First sentence (or first 80 chars) of the description, used to
     populate the short summary that consumers still expect. */
  const deriveShort = (text) => {
    const trimmed = text.trim();
    const firstSentence = trimmed.split(/(?<=[.!?])\s+/)[0] || trimmed;
    return firstSentence.slice(0, 80).trim();
  };

  const handleSave = () => {
    const cleanName = name.trim();
    const cleanDesc = desc.trim();
    const short = deriveShort(cleanDesc);
    if (isEdit) {
      onSave({ label: cleanName, short, desc: cleanDesc });
    } else {
      onSave({ key: deriveKey(cleanName), label: cleanName, short, desc: cleanDesc });
    }
  };

  return (
    <div className="modal-veil" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{maxWidth: 560, width: "94vw"}}>
        <div className="modal-head">
          <div style={{width:32,height:32,borderRadius:8,background:"var(--accent-soft)",color:"var(--accent-ink)",display:"grid",placeItems:"center"}}>
            <Icon n={isEdit ? "edit-3" : "plus"} s={16}/>
          </div>
          <h3>{isEdit ? `Edit category — ${initial.label}` : "New company category"}</h3>
        </div>
        <div className="modal-body">
          <div className="field">
            <label>Name <span className="req">*</span></label>
            <input type="text" value={name} onChange={e=>setName(e.target.value)} placeholder="e.g. Category E" autoFocus/>
          </div>

          <div className="field" style={{marginBottom:0}}>
            <label>Description <span className="req">*</span></label>
            <textarea
              value={desc} onChange={e=>setDesc(e.target.value)}
              placeholder="Define what makes a company fit this category — thresholds, examples, regulatory references…"
              style={{minHeight:120}}
            />
          </div>
        </div>
        <div className="modal-foot">
          <button className="btn" onClick={onClose}>Cancel</button>
          <button className="btn primary" disabled={!canSave} onClick={handleSave}>
            <Icon n="check" s={13}/> {isEdit ? "Save changes" : "Create category"}
          </button>
        </div>
      </div>
    </div>
  );
};

/* ====== Delete confirmation ====== */
const DeleteCompanyCategoryModal = ({ cat, usedCount, onClose, onConfirm }) => (
  <div className="modal-veil" onClick={onClose}>
    <div className="modal" onClick={e=>e.stopPropagation()}>
      <div className="modal-head">
        <div style={{width:32,height:32,borderRadius:8,background:"var(--danger-soft)",color:"var(--danger-ink)",display:"grid",placeItems:"center"}}>
          <Icon n="trash" s={16}/>
        </div>
        <h3>Delete category?</h3>
      </div>
      <div className="modal-body">
        <p style={{margin:"0 0 12px"}}>
          <b>{cat.label}</b> (<span className="mono">{cat.key}</span>) will be removed from the catalog.
        </p>
        {usedCount > 0 ? (
          <div className="banner danger">
            <div className="b-ico"><Icon n="alert-triangle" s={15}/></div>
            <div className="b-body">
              <span className="b-title">Used by {usedCount} project{usedCount>1?"s":""}</span>
              Existing projects keep this label, but new projects can't pick this category. Recommended: only delete custom categories you added yourself — never the default A/B/C/D.
            </div>
          </div>
        ) : (
          <div className="banner muted">
            <div className="b-ico"><Icon n="info" s={14}/></div>
            <div className="b-body">Not used by any project — safe to delete.</div>
          </div>
        )}
      </div>
      <div className="modal-foot">
        <button className="btn" onClick={onClose}>Cancel</button>
        <button className="btn danger solid" onClick={onConfirm}>
          <Icon n="trash" s={13}/> Delete
        </button>
      </div>
    </div>
  </div>
);

/* ====== Company Categories Screen ====== */
const CompanyCategoryScreen = ({ state, nav }) => {
  /* CATEGORY_INFO is an object keyed by single letter — flatten into array for the table */
  const toList = (obj) => Object.entries(obj).map(([k, v]) => ({ key:k, ...v }));
  const [catalog, setCatalog] = React.useState(toList(CATEGORY_INFO));
  const [modal, setModal]     = React.useState(null);

  /* count projects using each category */
  const usage = React.useMemo(() => {
    const map = {};
    state.projects.forEach(p => {
      if (p.category) map[p.category] = (map[p.category] || 0) + 1;
    });
    return map;
  }, [state.projects, catalog]);

  const handleAdd = (payload) => {
    const { key, ...rest } = payload;
    setCatalog(prev => [...prev, { key, ...rest }]);
    CATEGORY_INFO[key] = rest;
    nav.toast(`Category ${key} created`, "ok");
    nav.log && nav.log({ action:"edit", obj:`Company Category ${key}`, detail:`Created category "${payload.label}"`, severity:"critical" });
    setModal(null);
  };

  const handleEdit = (key, payload) => {
    const { key:_k, ...rest } = payload;
    setCatalog(prev => prev.map(c => c.key === key ? { ...c, ...rest } : c));
    CATEGORY_INFO[key] = { ...(CATEGORY_INFO[key] || {}), ...rest };
    nav.toast(`Category ${key} updated`, "ok");
    nav.log && nav.log({ action:"edit", obj:`Company Category ${key}`, detail:`Updated · ${Object.keys(rest).join(", ")}`, severity:"critical" });
    setModal(null);
  };

  const handleDelete = (key) => {
    setCatalog(prev => prev.filter(c => c.key !== key));
    delete CATEGORY_INFO[key];
    nav.toast(`Category ${key} deleted`, "warn");
    nav.log && nav.log({ action:"delete", obj:`Company Category ${key}`, detail:`Deleted category`, severity:"critical" });
    setModal(null);
  };

  /* Sort by key (A, B, C, D, then any custom) */
  const sorted = catalog.slice().sort((a, b) => a.key.localeCompare(b.key));

  return (
    <>
      <div className="page-head">
        <div className="page-title-row">
          <h1 className="page-title">Company Categories</h1>
          <span className="badge mono">{sorted.length} categories</span>
          <div className="page-actions">
            <button className="btn primary" onClick={()=>setModal({type:"add"})}>
              <Icon n="plus" s={13}/> New category
            </button>
          </div>
        </div>
      </div>

      <div className="page-body">
        {sorted.length === 0 ? (
          <div className="card">
            <EmptyState icon="shield" title="No categories yet"
              sub="Add at least one before users can classify projects."
              cta={<button className="btn primary" onClick={()=>setModal({type:"add"})}><Icon n="plus" s={13}/> New category</button>}/>
          </div>
        ) : (
          <div className="card">
            <table className="tbl">
              <thead><tr>
                <th style={{width:200}}>Name</th>
                <th>Description</th>
                <th style={{width:100,textAlign:"center"}}>Used by</th>
                <th style={{width:140,textAlign:"right"}}></th>
              </tr></thead>
              <tbody>
                {sorted.map(cat => {
                  const used = usage[cat.key] || 0;
                  const isDefault = ["A","B","C","D"].includes(cat.key);
                  return (
                    <tr key={cat.key}>
                      <td>
                        <b>{cat.label}</b>
                      </td>
                      <td>
                        <div style={{fontSize:12.5,color:"var(--ink-2)",lineHeight:1.5}}>
                          {cat.desc || <span className="muted">—</span>}
                        </div>
                      </td>
                      <td style={{textAlign:"center"}}>
                        {used > 0
                          ? <span className="sbadge accent">{used}</span>
                          : <span className="muted" style={{fontSize:12}}>—</span>}
                      </td>
                      <td style={{textAlign:"right"}}>
                        <div style={{display:"inline-flex",gap:6}}>
                          <button className="btn sm" onClick={()=>setModal({type:"edit", cat})}>
                            <Icon n="edit-3" s={11}/> Edit
                          </button>
                          <button
                            className="btn sm danger"
                            disabled={isDefault && used > 0}
                            title={isDefault && used > 0 ? "Default category in use — cannot delete" : "Delete"}
                            onClick={()=>setModal({type:"delete", cat, used})}>
                            <Icon n="trash" s={11}/>
                          </button>
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {modal?.type === "add" && (
        <CompanyCategoryFormModal
          existingKeys={catalog.map(c => c.key)}
          onClose={()=>setModal(null)}
          onSave={handleAdd}
        />
      )}
      {modal?.type === "edit" && (
        <CompanyCategoryFormModal
          initial={modal.cat}
          existingKeys={catalog.map(c => c.key)}
          onClose={()=>setModal(null)}
          onSave={(payload)=>handleEdit(modal.cat.key, payload)}
        />
      )}
      {modal?.type === "delete" && (
        <DeleteCompanyCategoryModal cat={modal.cat} usedCount={modal.used || 0}
          onClose={()=>setModal(null)}
          onConfirm={()=>handleDelete(modal.cat.key)}
        />
      )}
    </>
  );
};

Object.assign(window, { CompanyCategoryScreen, CompanyCategoryFormModal, DeleteCompanyCategoryModal });
