/* ───────────────────────── CEMETERY · MODERATION QUEUE ───────────────────────── */
const MOD_SEED = [
  {id:1, type:"Photo", rec:"Eleanor M. Hayes", plot:"H-214", by:"Susan Hayes", rel:"Granddaughter", email:"susan.h@email.com", note:"Grandma at the lake house, summer of 1979. We'd love this on her page.", img:true, when:"2 hours ago"},
  {id:2, type:"Fact", rec:"Sgt. Raymond Pruitt", plot:"H-031", by:"VFW Post 412", rel:"Veterans organization", email:"post412@vfw.org", note:"Raymond was awarded the Bronze Star in 1969. Please add it to his service record.", img:false, when:"5 hours ago"},
  {id:3, type:"Tribute", rec:"Clara Whitfield", plot:"A-118", by:"Anonymous", rel:"Former student", email:"—", note:"She taught me to read in the third grade. I became a teacher because of her. Thank you, Mrs. Whitfield.", img:false, when:"Yesterday"},
  {id:4, type:"Photo", rec:"Walter J. Abbott", plot:"C-042", by:"Mark Abbott", rel:"Son", email:"mabbott@email.com", note:"Dad in front of the hardware store he ran for 35 years.", img:true, when:"2 days ago"},
];

const SUB_KEY = "tendmory_photos_wilkers";
function loadSubs(){ try{ return JSON.parse(localStorage.getItem(SUB_KEY)||"[]"); }catch(e){ return []; } }
function saveSubs(a){ try{ localStorage.setItem(SUB_KEY, JSON.stringify(a)); }catch(e){} }

function Moderation(){
  const [items,setItems] = useState(MOD_SEED);
  const [leaving,setLeaving] = useState(null);
  const [tally,setTally] = useState({approved:0,rejected:0});
  const [declining,setDeclining] = useState(null);

  // pull real visitor photo submissions (from the public tribute page) into the queue
  useEffect(()=>{
    const subs = loadSubs().filter(s=>s.status==="pending");
    if(!subs.length) return;
    setItems(list=>{
      const have = new Set(list.map(i=>i.subId).filter(Boolean));
      const add = subs.filter(s=>!have.has(s.id)).map((s,i)=>({
        id:"sub-"+s.id, subId:s.id, type:"Photo", rec:"Reverend Jack B. Wilkers", plot:"H-214",
        by:s.by||"A visitor", rel:"Visitor", email:"—", note:"Photo submitted from the public memorial page.",
        img:true, localImg:s.dataUrl, when:"Just now"
      }));
      if(!add.length) return list;
      const next=[...add,...list]; window.__setModCount&&window.__setModCount(next.length); return next;
    });
  },[]);

  const remove = (item, kind)=>{
    setLeaving(item.id);
    // reflect decision back to the tribute page via shared storage
    if(item.subId){
      const arr = loadSubs();
      if(kind==="approve"){ const s=arr.find(x=>x.id===item.subId); if(s) s.status="approved"; saveSubs(arr); }
      else { saveSubs(arr.filter(x=>x.id!==item.subId)); }
    }
    setTimeout(()=>{
      setItems(list=>{ const next=list.filter(i=>i.id!==item.id); window.__setModCount&&window.__setModCount(next.length); return next; });
      setTally(t=>({...t, [kind==="approve"?"approved":"rejected"]: t[kind==="approve"?"approved":"rejected"]+1}));
      setLeaving(null);
    },320);
  };

  const act = (item, kind)=>{
    if(kind==="reject"){ setDeclining(item); return; }
    remove(item, kind);
    window.__toast && window.__toast({label:"Published", title:item.type+" approved", sub:item.rec+" · now live on the memorial"});
  };

  return (
    <div className="fade-in">
      <div className="page-head">
        <div>
          <div className="eyebrow">Cemetery Workspace</div>
          <h1>Moderation</h1>
          <div className="sub">{items.length} submission{items.length===1?"":"s"} awaiting your review · {tally.approved} approved today</div>
        </div>
      </div>

      <div className="mod-intro">
        <div className="mi">🛡</div>
        <div>
          <h3>You decide what goes public</h3>
          <p>Nothing a visitor submits appears on a memorial until your team approves it.</p>
        </div>
        <div className="mod-flow">
          <span className="fstep">Visitor submits</span>
          <span className="farr">→</span>
          <span className="fstep">Cemetery reviews</span>
          <span className="farr">→</span>
          <span className="fstep" style={{borderColor:"color-mix(in oklab,var(--ok) 40%,transparent)",color:"var(--ok)"}}>Published</span>
        </div>
      </div>

      {items.length===0 ? (
        <div className="card mod-empty">
          <div className="me">✓</div>
          <h3 style={{fontSize:20}}>You're all caught up</h3>
          <p className="muted" style={{marginTop:6}}>{tally.approved} approved · {tally.rejected} declined today. New submissions will land here.</p>
        </div>
      ) : items.map(it=>(
        <div key={it.id} className={"mod-card"+(leaving===it.id?" leaving":"")}>
          <div className="mod-thumb">{it.img ? <img src={it.localImg || (it.id%2? "/images/grounds-rows.jpg":"/images/grounds-hero.jpg")} alt="" /> : (it.type==="Fact"?"★":"❝")}</div>
          <div className="mod-main">
            <div className="mod-top">
              <span className={"mod-type "+it.type.toLowerCase()}>{it.type}</span>
              <span className="mod-for">{it.rec} <span>· {it.plot}</span></span>
              <span className="mod-when">{it.when}</span>
            </div>
            <div className="mod-note">{it.type==="Fact"?"“"+it.note+"”":it.type==="Tribute"?"“"+it.note+"”":it.note}</div>
            <div className="mod-by">Submitted by <b>{it.by}</b> · {it.rel}{it.email!=="—"?" · "+it.email:""}</div>
          </div>
          <div className="mod-acts">
            <button className="mod-btn approve" onClick={()=>act(it,"approve")}>✓ Approve</button>
            <button className="mod-btn reject" onClick={()=>act(it,"reject")}>✕ Decline</button>
          </div>
        </div>
      ))}

      {declining && <DeclineModal item={declining} onClose={()=>setDeclining(null)} onSend={(item,reason)=>{
        setDeclining(null);
        remove(item,"reject");
        window.__toast && window.__toast({label:"Declined · email sent", title:item.type+" declined", sub:(item.email!=="—"?item.email:item.by)+" · reason delivered"});
      }} />}
    </div>
  );
}

const DECLINE_REASONS = [
  "Couldn't verify this is accurate",
  "Photo quality is too low",
  "Not appropriate for the memorial",
  "Possible duplicate",
  "Need proof of relationship",
];

function DeclineModal({item, onClose, onSend}){
  const [reason,setReason] = useState("");
  const hasEmail = item.email && item.email!=="—";
  return (
    <div className="overlay" onClick={(e)=>{if(e.target.classList.contains("overlay"))onClose();}}>
      <div className="modal" style={{width:"min(520px,100%)"}}>
        <div className="modal-h">
          <div style={{width:34,height:34,borderRadius:9,background:"color-mix(in oklab,var(--hold) 14%,var(--paper))",color:"var(--hold)",display:"grid",placeItems:"center",flex:"none"}}>✕</div>
          <h3>Decline this {item.type.toLowerCase()}</h3>
          <button className="x" onClick={onClose}>×</button>
        </div>
        <div className="modal-b">
          <div className="import-row" style={{marginBottom:16}}>
            <div className="fi" style={{background:"color-mix(in oklab,var(--hold) 12%,var(--paper))",color:"var(--hold)"}}>{item.type==="Fact"?"★":item.type==="Tribute"?"❝":"▣"}</div>
            <div style={{flex:1}}>
              <div className="fn">{item.rec} <span className="muted" style={{fontFamily:"var(--font-mono)",fontSize:11.5}}>· {item.plot}</span></div>
              <div className="fm" style={{fontFamily:"var(--font-body)",letterSpacing:0}}>From {item.by} · {item.rel}</div>
            </div>
          </div>

          <label className="flbl">Reason — this goes to the submitter</label>
          <div style={{display:"flex",flexWrap:"wrap",gap:7,margin:"2px 0 12px"}}>
            {DECLINE_REASONS.map(r=>(
              <button key={r} className={"chip"+(reason===r?" on":"")} style={{fontWeight:500,fontSize:12}} onClick={()=>setReason(r)}>{r}</button>
            ))}
          </div>
          <textarea className="finp" rows={4} value={reason} onChange={e=>setReason(e.target.value)} placeholder="Add a note explaining what needs to change…" style={{resize:"vertical",lineHeight:1.5}} />

          <div style={{display:"flex",alignItems:"center",gap:10,marginTop:14,padding:"11px 13px",borderRadius:11,background:hasEmail?"color-mix(in oklab,var(--info) 8%,var(--paper))":"var(--paper-2)",border:"1px solid "+(hasEmail?"color-mix(in oklab,var(--info) 24%,transparent)":"var(--line)")}}>
            <div style={{fontWeight:700,color:hasEmail?"#2B5573":"var(--faint)",fontSize:14}}>✉</div>
            <span className="muted" style={{fontSize:12.5}}>{hasEmail? <>Emails to <b style={{color:"var(--ink)"}}>{item.email}</b> with your note and a link to resubmit.</> : "Submitter left no email — they'll see the reason if they return to the page."}</span>
          </div>

          <div style={{display:"flex",gap:10,marginTop:16}}>
            <button className="btn ghost" style={{flex:1,justifyContent:"center"}} onClick={onClose}>Cancel</button>
            <button className="btn primary" style={{flex:2,justifyContent:"center",opacity:reason.trim()?1:.5,pointerEvents:reason.trim()?"auto":"none",background:"var(--hold)"}} onClick={()=>onSend(item,reason.trim())}>✉ Send &amp; decline</button>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Moderation });
