/* ============ Modals ============ */

/* Activate modal — confirm + optional comment.
   When Admin has corrected Category / Risk inline, `edits` is passed so the
   modal can summarise the change before activating. */
const ApproveModal = ({ project, edits, onClose, onConfirm }) => {
  const [comment, setComment] = React.useState("");
  return (
    <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(--ok-soft)",color:"var(--ok-ink)",display:"grid",placeItems:"center"}}>
            <Icon n="thumbs-up" s={16}/>
          </div>
          <h3>{edits ? "Save edits & publish?" : "Publish project?"}</h3>
        </div>
        <div className="modal-body">
          <p style={{margin:"0 0 14px"}}>
            <b>{project.name}</b> will become an <b>Active</b> project under{" "}
            <b>{entityById(project.entityId).name}</b>. Members will be notified.
          </p>
          {edits && (
            <div className="banner warn" style={{marginBottom:14}}>
              <div className="b-ico"><Icon n="edit-3" s={14}/></div>
              <div className="b-body">
                <span className="b-title">Inline corrections applied</span>
                {edits.category && edits.category !== project.category && (
                  <div>Category: <s>{project.category}</s> → <b>{edits.category}</b></div>
                )}
                {edits.riskLevel && edits.riskLevel !== project.riskLevel && (
                  <div>Risk Level: <s>{project.riskLevel || "—"}</s> → <b>{edits.riskLevel}</b></div>
                )}
                <div className="help" style={{marginTop:4}}>Fix-then-publish replaces Reject &amp; resubmit.</div>
              </div>
            </div>
          )}
          <div className="field" style={{marginBottom:0}}>
            <label>Comment</label>
            <textarea
              placeholder="e.g. Looks good — please complete planning by end of next week."
              value={comment}
              onChange={e=>setComment(e.target.value)}
            />
            <div className="help">A notification is sent to the Project Creator and all members.</div>
          </div>
        </div>
        <div className="modal-foot">
          <button className="btn" onClick={onClose}>Cancel</button>
          <button className="btn ok" onClick={()=>onConfirm(comment)}>
            <Icon n="check" s={14}/> {edits ? "Save & Publish" : "Publish"}
          </button>
        </div>
      </div>
    </div>
  );
};

/* Change-password modal — current + new + confirm, each with show/hide toggle.
   POC only: validates locally and toasts; no real credential store. */
const ChangePasswordModal = ({ onClose, onSave }) => {
  const [cur, setCur]   = React.useState("");
  const [next, setNext] = React.useState("");
  const [conf, setConf] = React.useState("");
  const [show, setShow] = React.useState({ cur:false, next:false, conf:false });
  const [error, setError] = React.useState("");

  /* Render inline (not a nested component) so React doesn't remount the inputs
     on each keystroke — a nested component would drop focus after one character. */
  const pwField = (k, value, setValue, placeholder, autoFocus) => (
    <div className="pw-wrap">
      <input type={show[k] ? "text" : "password"} value={value} autoFocus={autoFocus}
        onChange={e=>{setValue(e.target.value); setError("");}}
        placeholder={placeholder}/>
      <button type="button" className="pw-toggle"
        onClick={()=>setShow(s=>({...s, [k]:!s[k]}))}
        title={show[k] ? "Hide" : "Show"} aria-label={show[k] ? "Hide password" : "Show password"}>
        <Icon n={show[k] ? "eye-off" : "eye"} s={15}/>
      </button>
    </div>
  );

  const submit = () => {
    if (!cur)               { setError("Enter your current password."); return; }
    if (next.length < 6)    { setError("New password must be at least 6 characters."); return; }
    if (next !== conf)      { setError("New password and confirmation do not match."); return; }
    if (next === cur)       { setError("New password must differ from the current one."); return; }
    onSave();
  };

  return (
    <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(--panel-2)",color:"var(--ink)",display:"grid",placeItems:"center"}}>
            <Icon n="lock" s={16}/>
          </div>
          <h3>Change password</h3>
        </div>
        <div className="modal-body" style={{display:"flex",flexDirection:"column",gap:14}}>
          <div className="field" style={{marginBottom:0}}>
            <label>Current password</label>
            {pwField("cur", cur, setCur, "••••••••", true)}
          </div>
          <div className="field" style={{marginBottom:0}}>
            <label>New password</label>
            {pwField("next", next, setNext, "At least 6 characters", false)}
          </div>
          <div className="field" style={{marginBottom:0}}>
            <label>Confirm new password</label>
            {pwField("conf", conf, setConf, "Re-enter new password", false)}
          </div>
          {error && <div className="field" style={{marginBottom:0}}><div className="err"><Icon n="alert" s={13}/> {error}</div></div>}
        </div>
        <div className="modal-foot">
          <button className="btn" onClick={onClose}>Cancel</button>
          <button className="btn primary" onClick={submit}><Icon n="check" s={14}/> Update password</button>
        </div>
      </div>
    </div>
  );
};

/* New Entity modal — 3 fields only.
   Matches the pattern of Service Types / Company Categories / SOP Templates
   form modals. (Was a side drawer previously.) */
const NewEntityModal = ({ onClose, onSave, existingTaxIds }) => {
  const [name, setName] = React.useState("");
  const [taxId, setTaxId] = React.useState("");
  const [desc, setDesc] = React.useState("");
  const [taxBlurred, setTaxBlurred] = React.useState(false);

  const taxIdDigits = taxId.replace(/\D/g,"");
  const taxIdValid = taxIdDigits.length === 13;
  const taxIdExists = taxBlurred && taxIdValid && existingTaxIds.includes(taxIdDigits);
  const taxIdShortError = taxBlurred && taxId.length > 0 && !taxIdValid;
  const conflictEntity = taxIdExists ? ENTITIES_SEED.find(e=>e.taxId===taxIdDigits) : null;

  const canSave = name.trim().length >= 2 && taxIdValid && !taxIdExists;

  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="plus" s={16}/>
          </div>
          <h3>New entity</h3>
        </div>
        <div className="modal-body">
          <div className="field">
            <label>Entity name <span className="req">*</span></label>
            <input type="text" value={name} onChange={e=>setName(e.target.value)} placeholder="e.g. Acme Co., Ltd. — accepts Thai or English" autoFocus/>
            <div className="help">Use the client's full legal name. Edit later if it changes (a history entry is recorded).</div>
          </div>

          <div className="field">
            <label>Tax ID <span className="req">*</span></label>
            <input type="text" value={taxId} onChange={e=>setTaxId(e.target.value)} onBlur={()=>setTaxBlurred(true)} placeholder="13-digit Thai legal entity ID" inputMode="numeric"/>
            {taxIdShortError && <div className="err"><Icon n="alert" s={12}/> Tax ID must be exactly 13 digits.</div>}
            {taxIdExists && <div className="err"><Icon n="alert" s={12}/> Tax ID already exists: <b style={{marginLeft:4}}>{conflictEntity?.name}</b></div>}
            {!taxIdShortError && !taxIdExists && <div className="help">Must be unique across all entities.</div>}
          </div>

          <div className="field" style={{marginBottom:0}}>
            <label>Description</label>
            <textarea value={desc} maxLength={ENTITY_DESC_MAX}
              onChange={e=>setDesc(e.target.value.slice(0, ENTITY_DESC_MAX))}
              placeholder="Notes, e.g. 'Renamed from XYZ Co. in 2024' or 'Group consolidation with…' "/>
            <div className="help" style={{display:"flex",justifyContent:"space-between"}}>
              <span>Useful for renaming history, group context, regulator notes.</span>
              <span className="mono" style={{color: desc.length >= ENTITY_DESC_MAX ? "var(--danger-ink)" : "var(--muted)"}}>
                {desc.length}/{ENTITY_DESC_MAX}
              </span>
            </div>
          </div>
        </div>
        <div className="modal-foot">
          <button className="btn" onClick={onClose}>Cancel</button>
          <button className="btn primary" disabled={!canSave} onClick={()=>onSave({name:name.trim(),taxId:taxIdDigits,desc:desc.trim()})}>
            <Icon n="check" s={14}/> Save entity
          </button>
        </div>
      </div>
    </div>
  );
};

/* Add Creator (Supervisor) modal */
const AddCreatorModal = ({ entity, onClose, onAdd }) => {
  const [pick, setPick] = React.useState(null);
  const existing = entity.creators || [];
  const eligible = USERS.filter(u => u.role==="Supervisor" && !existing.includes(u.id));
  return (
    <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(--accent-soft)",color:"var(--accent-ink)",display:"grid",placeItems:"center"}}>
            <Icon n="users" s={16}/>
          </div>
          <h3>Add Project Creator</h3>
        </div>
        <div className="modal-body">
          {eligible.length === 0 ? (
            <div className="empty" style={{padding:20}}>
              <div className="em-illu" style={{width:40,height:40}}><Icon n="users" s={16}/></div>
              <div className="em-title" style={{fontSize:13}}>All Supervisors already added</div>
            </div>
          ) : (
            <div className="stack-sm" style={{maxHeight:280,overflowY:"auto"}}>
              {eligible.map(u => (
                <button key={u.id}
                  onClick={()=>setPick(u.id)}
                  style={{
                    display:"flex",alignItems:"center",gap:10,padding:"10px 12px",border:"1px solid var(--line)",
                    borderRadius:"var(--radius)",background:pick===u.id?"var(--accent-soft)":"#fff",
                    borderColor:pick===u.id?"var(--accent)":"var(--line)",cursor:"pointer",textAlign:"left",width:"100%"
                  }}>
                  <Avatar id={u.id} name={u.name} size="md"/>
                  <div style={{flex:1}}>
                    <div style={{fontWeight:500}}>{u.name}</div>
                    <div className="muted" style={{fontSize:11,fontFamily:"var(--mono)"}}>{u.email}</div>
                  </div>
                  <span className="badge">Supervisor</span>
                  {pick===u.id && <Icon n="check" s={16} c="" />}
                </button>
              ))}
            </div>
          )}
        </div>
        <div className="modal-foot">
          <button className="btn" onClick={onClose}>Cancel</button>
          <button className="btn primary" disabled={!pick} onClick={()=>onAdd(pick)}>
            <Icon n="plus" s={14}/> Add as Creator
          </button>
        </div>
      </div>
    </div>
  );
};

/* User picker modal for project members */
const MemberPickerModal = ({ already, onClose, onSelect }) => {
  const [q, setQ] = React.useState("");
  const eligible = USERS
    .filter(u => (u.role === "Supervisor" || u.role === "Staff") && !already.includes(u.id))
    .filter(u => !q || u.name.toLowerCase().includes(q.toLowerCase()) || u.email.toLowerCase().includes(q.toLowerCase()));
  return (
    <div className="modal-veil" onClick={onClose}>
      <div className="modal lg" onClick={e=>e.stopPropagation()}>
        <div className="modal-head">
          <h3>Add members</h3>
          <button className="icon-btn" onClick={onClose}><Icon n="x" s={16}/></button>
        </div>
        <div className="modal-body" style={{paddingTop:14}}>
          <div className="input full" style={{marginBottom:12}}>
            <Icon n="search" s={14} c="muted"/>
            <input placeholder="Search Supervisors and Staff…" value={q} onChange={e=>setQ(e.target.value)} autoFocus/>
          </div>
          <div className="stack-sm" style={{maxHeight:340,overflowY:"auto"}}>
            {eligible.length === 0 && <div className="empty" style={{padding:16}}>No matches</div>}
            {eligible.map(u => (
              <button key={u.id} onClick={()=>onSelect(u.id)}
                style={{display:"flex",alignItems:"center",gap:10,padding:"9px 10px",border:"1px solid var(--line)",
                  borderRadius:"var(--radius)",background:"#fff",cursor:"pointer",textAlign:"left",width:"100%"}}>
                <Avatar id={u.id} name={u.name} size="md"/>
                <div style={{flex:1}}>
                  <div style={{fontWeight:500}}>{u.name}</div>
                  <div className="muted" style={{fontSize:11,fontFamily:"var(--mono)"}}>{u.email}</div>
                </div>
                <span className="badge">{u.role}</span>
                <Icon n="plus" s={14}/>
              </button>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

/* Hand-off to Admin for activation (Creator → Admin queue, per MTG3) */
const SubmitModal = ({ project, 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(--warn-soft)",color:"var(--warn-ink)",display:"grid",placeItems:"center"}}>
          <Icon n="send" s={16}/>
        </div>
        <h3>Send to Admin for activation?</h3>
      </div>
      <div className="modal-body">
        <p style={{margin:0}}>
          The draft of <b>{project.name}</b> will be routed to the Approval Center for Admin to activate.
          Both you and Admin can keep editing — and Admin can correct Category / Risk inline before activating.
        </p>
      </div>
      <div className="modal-foot">
        <button className="btn" onClick={onClose}>Cancel</button>
        <button className="btn primary" onClick={onConfirm}><Icon n="send" s={13}/> Send</button>
      </div>
    </div>
  </div>
);

/* Delete-draft confirm modal — only for status=draft|rejected */
const DeleteDraftModal = ({ project, onClose, onConfirm }) => {
  const [confirmText, setConfirmText] = React.useState("");
  const required = "DELETE";
  const valid = confirmText.trim().toUpperCase() === required;
  return (
    <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 draft?</h3>
        </div>
        <div className="modal-body">
          <p style={{margin:"0 0 12px"}}>
            The draft of <b>{project.name}</b> will be permanently removed. Members will lose access.
          </p>
          <div className="banner danger" style={{marginBottom:14}}>
            <div className="b-ico"><Icon n="alert-triangle" s={15}/></div>
            <div className="b-body">
              <span className="b-title">This cannot be undone</span>
              Only drafts that have not been approved can be deleted. If you change your mind later, you'll have to start a new draft from scratch.
            </div>
          </div>
          <div className="field" style={{marginBottom:0}}>
            <label>Type <span className="mono" style={{background:"var(--panel-2)",padding:"1px 5px",borderRadius:3,fontSize:11}}>DELETE</span> to confirm</label>
            <input type="text" value={confirmText} onChange={e=>setConfirmText(e.target.value)} placeholder="DELETE" autoFocus/>
          </div>
        </div>
        <div className="modal-foot">
          <button className="btn" onClick={onClose}>Cancel</button>
          <button className="btn danger solid" disabled={!valid} onClick={onConfirm}>
            <Icon n="trash" s={13}/> Delete draft permanently
          </button>
        </div>
      </div>
    </div>
  );
};

/* Decline access request — reason is MANDATORY per req §3.4/§4.10
   ("Reject ต้องระบุเหตุผล + แจ้งเตือนผู้ขอกลับ"). Used for both single and
   bulk declines in the Approval Center. */
const DeclineReasonModal = ({ count, requesterName, projectName, onClose, onConfirm }) => {
  const [reason, setReason] = React.useState("");
  const valid = reason.trim().length >= 5;
  const bulk = count > 1;
  return (
    <div className="modal-veil" onClick={onClose}>
      <div className="modal" onClick={e=>e.stopPropagation()} style={{maxWidth:480, width:"94vw"}}>
        <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="x" s={16}/>
          </div>
          <h3>{bulk ? `Decline ${count} requests` : "Decline access request"}</h3>
        </div>
        <div className="modal-body">
          <p style={{margin:"0 0 12px",fontSize:13}}>
            {bulk
              ? <>You are declining <b>{count} access requests</b>. One reason will be recorded for all of them.</>
              : <><b>{requesterName}</b> requested access to <b>{projectName}</b>.</>}
          </p>
          <div className="field" style={{marginBottom:0}}>
            <label>Reason <span className="req">*</span></label>
            <textarea autoFocus value={reason} onChange={e=>setReason(e.target.value)}
              placeholder="e.g. Not assigned to this engagement — request again via your Supervisor if needed."/>
            <div className="help">Required (min 5 characters). The requester is notified with this reason, and it is recorded in the Activity Log.</div>
          </div>
        </div>
        <div className="modal-foot">
          <button className="btn" onClick={onClose}>Cancel</button>
          <button className="btn danger solid" disabled={!valid} onClick={()=>onConfirm(reason.trim())}>
            <Icon n="x" s={12}/> {bulk ? `Decline ${count} & notify` : "Decline & notify"}
          </button>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { ApproveModal, NewEntityModal, AddCreatorModal, MemberPickerModal, SubmitModal, DeleteDraftModal, DeclineReasonModal, ChangePasswordModal });
