/* ───────────────────────── CEMETERY · DOCUMENT TEMPLATES ───────────────────────── */
/* Merge fields a template can carry. `lock:true` = always pulled from the record (not hand-edited). */
const FIELD_LIBRARY = [
  {key:"buyer_name",   label:"Buyer name"},
  {key:"buyer_email",  label:"Buyer email"},
  {key:"buyer_phone",  label:"Buyer phone"},
  {key:"deceased",     label:"Deceased name"},
  {key:"plot",         label:"Plot", lock:true},
  {key:"section",      label:"Section", lock:true},
  {key:"price",        label:"Price"},
  {key:"plan",         label:"Payment plan"},
  {key:"sale_date",    label:"Sale date"},
  {key:"officiant",    label:"Officiant"},
  {key:"care_terms",   label:"Care terms"},
];
const FIELD_LABEL = Object.fromEntries(FIELD_LIBRARY.map(f=>[f.key,f.label]));

const DEFAULT_TEMPLATES = [
  {id:"deed", name:"Right of Interment Deed", kind:"Deed", builtin:true, pages:2,
   fields:["buyer_name","plot","section","sale_date"], editable:["buyer_name","sale_date"]},
  {id:"purchase", name:"Purchase Agreement", kind:"Contract", builtin:true, pages:3,
   fields:["buyer_name","buyer_email","plot","price","plan","sale_date"], editable:["buyer_name","price","plan","sale_date"]},
  {id:"preneed", name:"Pre-Need Disclosure (state form)", kind:"Compliance", builtin:true, pages:2, preneed:true,
   fields:["buyer_name","buyer_phone","plot","price","plan"], editable:["price","plan"]},
  {id:"care", name:"Care & Maintenance Authorization", kind:"Authorization", builtin:true, pages:1,
   fields:["buyer_name","plot","care_terms"], editable:["care_terms"]},
];

function loadTemplates(){
  try{ const s=JSON.parse(localStorage.getItem("tendmory_templates")||"null"); if(s&&s.length) return s; }catch(e){}
  return DEFAULT_TEMPLATES;
}
function saveTemplates(t){ try{ localStorage.setItem("tendmory_templates", JSON.stringify(t)); }catch(e){} }
window.__getTemplates = loadTemplates;

function Documents(){
  const [templates,setTemplates] = useState(loadTemplates);
  const [editing,setEditing] = useState(null);   // template being configured
  const [uploading,setUploading] = useState(false);
  const persist = (next)=>{ setTemplates(next); saveTemplates(next); };

  const addTemplate = (t)=>{ const id="tpl"+Date.now(); const next=[...templates,{...t,id}]; persist(next); setUploading(false); setEditing({...t,id}); window.__toast&&window.__toast({label:"Template added",title:t.name,sub:t.fields.length+" merge fields detected"}); };
  const updateTemplate = (t)=>{ persist(templates.map(x=>x.id===t.id?t:x)); setEditing(null); window.__toast&&window.__toast({label:"Template saved",title:t.name,sub:t.editable.length+" field"+(t.editable.length===1?"":"s")+" editable at sale"}); };
  const removeTemplate = (id)=>{ persist(templates.filter(x=>x.id!==id)); };

  return (
    <div className="fade-in">
      <div className="page-head">
        <div>
          <div className="eyebrow">Cemetery Workspace</div>
          <h1>Documents &amp; Templates</h1>
          <div className="sub">{templates.length} templates · auto-filled at sale, editable where you allow it</div>
        </div>
        <button className="btn primary" onClick={()=>setUploading(true)}>⤓ Upload a template</button>
      </div>

      <div className="mod-intro" style={{background:"linear-gradient(120deg,color-mix(in oklab,var(--info) 9%,var(--card)),var(--card))",borderColor:"color-mix(in oklab,var(--info) 22%,var(--line))"}}>
        <div className="mi" style={{background:"var(--info)"}}>▤</div>
        <div>
          <h3>Set it up once, reuse it forever</h3>
          <p>Upload a document, mark the blanks as merge fields, and choose which a clerk can edit at the moment of sale. Every sale fills the rest automatically.</p>
        </div>
        <div className="mod-flow">
          <span className="fstep">Upload</span><span className="farr">→</span>
          <span className="fstep">Map fields</span><span className="farr">→</span>
          <span className="fstep" style={{color:"var(--ok)",borderColor:"color-mix(in oklab,var(--ok) 40%,transparent)"}}>Reusable template</span>
        </div>
      </div>

      <div className="tpl-grid">
        {templates.map(t=>(
          <div key={t.id} className="tpl-card">
            <div className="tpl-top">
              <div className="tpl-ic">▤</div>
              <div style={{flex:1,minWidth:0}}>
                <div className="tpl-name">{t.name}</div>
                <div className="tpl-meta">{t.kind} · {t.pages} page{t.pages>1?"s":""} {t.builtin?"· standard":"· custom"}</div>
              </div>
              {t.preneed && <span className="pill reserved"><i className="pd"></i>Pre-need</span>}
            </div>
            <div className="tpl-fields">
              {t.fields.map(f=>(
                <span key={f} className={"tpl-chip"+(t.editable.includes(f)?" edit":"")} title={t.editable.includes(f)?"Editable at sale":"Auto-filled"}>
                  {t.editable.includes(f) && <span className="ec">✎</span>}{FIELD_LABEL[f]||f}
                </span>
              ))}
            </div>
            <div className="tpl-foot">
              <span className="muted" style={{fontSize:12}}>{t.editable.length} editable at sale</span>
              <div style={{display:"flex",gap:8}}>
                {!t.builtin && <button className="chip" onClick={()=>removeTemplate(t.id)}>Remove</button>}
                <button className="chip" onClick={()=>setEditing(t)}>Configure →</button>
              </div>
            </div>
          </div>
        ))}
      </div>

      {editing && <TemplateConfig template={editing} onClose={()=>setEditing(null)} onSave={updateTemplate} />}
      {uploading && <UploadTemplate onClose={()=>setUploading(false)} onAdd={addTemplate} />}
    </div>
  );
}

function TemplateConfig({template, onClose, onSave}){
  const [fields,setFields] = useState(template.fields);
  const [editable,setEditable] = useState(template.editable);
  const toggleField = (k)=>{
    const f = FIELD_LIBRARY.find(x=>x.key===k);
    setFields(fs=>fs.includes(k)?fs.filter(x=>x!==k):[...fs,k]);
    if(fields.includes(k)) setEditable(e=>e.filter(x=>x!==k));
  };
  const toggleEditable = (k)=>{
    const f = FIELD_LIBRARY.find(x=>x.key===k);
    if(f&&f.lock) return;
    setEditable(e=>e.includes(k)?e.filter(x=>x!==k):[...e,k]);
  };
  return (
    <div className="sheet" key={template.id}>
      <div className="sheet-h">
        <div style={{flex:1}}>
          <div className="eyebrow">{template.kind}</div>
          <div style={{fontFamily:"var(--font-display)",fontWeight:700,fontSize:18,marginTop:6}}>{template.name}</div>
        </div>
        <button className="x" onClick={onClose}>×</button>
      </div>
      <div className="sheet-b">
        <div className="tpl-preview"><div className="pg"><div className="ln w60"></div><div className="ln w90"></div><div className="ln w80"></div><div className="ln w40"></div><div className="sig"></div></div><span className="pv-tag">Document preview</span></div>

        <div className="sec-h"><h3>Merge fields</h3><div className="ln"></div><span className="cnt">{fields.length}</span></div>
        <p className="muted" style={{fontSize:12.5,marginBottom:10}}>Which blanks does this document fill in?</p>
        <div className="field-pick">
          {FIELD_LIBRARY.map(f=>(
            <div key={f.key} className={"fpick"+(fields.includes(f.key)?" on":"")} onClick={()=>toggleField(f.key)}>
              <div className="cbx">{fields.includes(f.key)?"✓":""}</div>{f.label}
            </div>
          ))}
        </div>

        <div className="sec-h"><h3>Editable at sale</h3><div className="ln"></div><span className="cnt">{editable.length}</span></div>
        <p className="muted" style={{fontSize:12.5,marginBottom:10}}>A clerk can adjust these at the moment of sale. The rest auto-fill from the record and lock.</p>
        <div style={{display:"flex",flexDirection:"column",gap:7}}>
          {fields.map(k=>{
            const f = FIELD_LIBRARY.find(x=>x.key===k); const locked = f&&f.lock;
            return (
              <div key={k} className="edit-toggle" onClick={()=>toggleEditable(k)} style={{opacity:locked?.55:1,cursor:locked?"not-allowed":"pointer"}}>
                <span>{FIELD_LABEL[k]}</span>
                {locked
                  ? <span className="muted" style={{fontSize:11,fontFamily:"var(--font-mono)"}}>always from record</span>
                  : <span className={"toggle"+(editable.includes(k)?" on":"")}><i></i></span>}
              </div>
            );
          })}
        </div>
      </div>
      <div className="sheet-foot">
        <button className="btn ghost" style={{flex:1,justifyContent:"center"}} onClick={onClose}>Cancel</button>
        <button className="btn primary" style={{flex:1,justifyContent:"center"}} onClick={()=>onSave({...template,fields,editable})}>Save template</button>
      </div>
    </div>
  );
}

function UploadTemplate({onClose, onAdd}){
  const [stage,setStage] = useState("drop"); // drop | scanning | name
  const [name,setName] = useState("");
  const [kind,setKind] = useState("Contract");
  const detected = ["buyer_name","plot","section","price","sale_date"];
  useEffect(()=>{ if(stage!=="scanning") return; const t=setTimeout(()=>setStage("name"),1400); return ()=>clearTimeout(t); },[stage]);
  return (
    <div className="overlay" onClick={(e)=>{if(e.target.classList.contains("overlay"))onClose();}}>
      <div className="modal" style={{width:"min(540px,100%)"}}>
        <div className="modal-h">
          <div style={{width:34,height:34,borderRadius:9,background:"color-mix(in oklab,var(--info) 12%,var(--paper))",color:"var(--info)",display:"grid",placeItems:"center",flex:"none"}}>▤</div>
          <h3>Upload a document template</h3>
          <button className="x" onClick={onClose}>×</button>
        </div>
        <div className="modal-b">
          {stage==="drop" && (
            <div className="fade-in">
              <div className="dropzone" onClick={()=>setStage("scanning")}>
                <div className="dzi">⬇</div>
                <b>Drop a Word or PDF document</b>
                <span>Your existing deed, contract, or authorization form</span>
                <div className="dz-sample">▤ maplewood_purchase_agreement.docx</div>
              </div>
              <p className="muted" style={{fontSize:12.5,marginTop:14}}>We'll scan it for blanks (e.g. “Buyer: ____”) and suggest merge fields you can confirm.</p>
            </div>
          )}
          {stage==="scanning" && (
            <div className="fade-in center" style={{padding:"26px 0"}}>
              <div className="spinner" style={{margin:"0 auto 16px"}}></div>
              <b style={{fontSize:15}}>Scanning for fields…</b>
              <p className="muted" style={{fontSize:13,marginTop:6}}>Detecting blanks and signature blocks</p>
            </div>
          )}
          {stage==="name" && (
            <div className="fade-in">
              <div className="import-row" style={{marginBottom:16}}>
                <div className="fi" style={{background:"color-mix(in oklab,var(--ok) 14%,var(--paper))",color:"var(--ok)"}}>✓</div>
                <div style={{flex:1}}><div className="fn">{detected.length} merge fields detected</div><div className="fm" style={{fontFamily:"var(--font-body)",letterSpacing:0}}>{detected.map(d=>FIELD_LABEL[d]).join(" · ")}</div></div>
              </div>
              <label className="flbl">Template name</label>
              <input className="finp" value={name} onChange={e=>setName(e.target.value)} placeholder="e.g. Maplewood Purchase Agreement" autoFocus style={{marginBottom:14}} />
              <label className="flbl">Type</label>
              <select className="finp" value={kind} onChange={e=>setKind(e.target.value)} style={{marginBottom:18}}>
                {["Contract","Deed","Compliance","Authorization","Other"].map(k=><option key={k} value={k}>{k}</option>)}
              </select>
              <button className="btn primary" style={{width:"100%",justifyContent:"center",opacity:name.trim()?1:.5,pointerEvents:name.trim()?"auto":"none"}}
                onClick={()=>onAdd({name:name.trim(),kind,pages:2,fields:detected,editable:detected.filter(d=>d!=="plot"&&d!=="section")})}>
                Add template →
              </button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Documents, FIELD_LIBRARY, FIELD_LABEL });
