/* ───────────────────────── TENDMORY · DEMO DATA + PRIMITIVES ───────────────────────── */
const { useState, useEffect, useRef, useMemo, useCallback } = React;

/* deterministic pseudo-random so the demo looks identical every load */
function mulberry32(a){return function(){a|=0;a=a+0x6D2B79F5|0;let t=Math.imul(a^a>>>15,1|a);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296;};}

const FIRST_M = ["James","Robert","John","William","Charles","George","Henry","Frank","Walter","Arthur","Albert","Harold","Raymond","Roy","Clarence","Earl","Joseph","Samuel","Theodore","Edward","Floyd","Leon","Chester","Howard","Glenn"];
const FIRST_F = ["Mary","Eleanor","Margaret","Helen","Dorothy","Ruth","Florence","Mildred","Edith","Alice","Esther","Clara","Gladys","Bertha","Lillian","Grace","Pearl","Agnes","Hazel","Edna","Vera","Beatrice","Lucille","Nora","Opal"];
const SUR = ["Hayes","Whitfield","Carver","Donnelly","Abbott","Pruitt","Galloway","Sutton","Merritt","Hollis","Beckett","Ransom","Calloway","Tillman","Vance","Wexler","Ashby","Crandall","Pickering","Maddox","Ellison","Thornbury","Quill","Easton","Lindqvist","Brennan","Castellano","Okafor","Nakamura","Delgado"];
const SECTIONS = [
  {id:"A", name:"Founders' Rest", x:8,  y:10, w:26, h:34, kind:"lawn"},
  {id:"B", name:"Maple Grove",    x:38, y:8,  w:26, h:28, kind:"lawn"},
  {id:"H", name:"Garden of Honor",x:68, y:10, w:24, h:30, kind:"veteran"},
  {id:"C", name:"Hillside",       x:8,  y:50, w:30, h:30, kind:"lawn"},
  {id:"G", name:"Chapel Lawn",    x:42, y:46, w:22, h:24, kind:"lawn"},
  {id:"R", name:"Memorial Ridge", x:68, y:48, w:24, h:34, kind:"lawn"},
];
const BRANCHES = ["U.S. Army","U.S. Navy","U.S. Marine Corps","U.S. Air Force","U.S. Coast Guard"];
const CONFLICTS = ["WWII","Korea","Vietnam","WWI"];
const STATUSES = ["occupied","available","reserved","hold","exhumated"];

function makeRecords(){
  const rnd = mulberry32(7);
  const recs = [];
  let id = 1000;
  for(const sec of SECTIONS){
    const cols = 9, rows = 7;
    for(let r=0;r<rows;r++){
      for(let c=0;c<cols;c++){
        const roll = rnd();
        let status;
        if(sec.kind==="veteran"){ status = roll<0.74?"occupied":(roll<0.9?"reserved":"available"); }
        else { status = roll<0.6?"occupied":(roll<0.72?"reserved":(roll<0.78?"hold":(roll<0.8?"exhumated":"available"))); }
        const plot = `${sec.id}-${(r*cols+c+1).toString().padStart(3,"0")}`;
        // map coordinates within the section box
        const px = sec.x + 3 + (c/(cols-1))*(sec.w-6);
        const py = sec.y + 4 + (r/(rows-1))*(sec.h-8);
        if(status==="available"){
          recs.push({id:++id, status, plot, section:sec, x:px, y:py, row:r, col:c, cols, name:null, listPrice: 1800+Math.floor(rnd()*9)*150, sizeW:sec.kind==="veteran"?4:3.5, sizeL:10, notes:""});
          continue;
        }
        const female = rnd()>0.5;
        const first = (female?FIRST_F:FIRST_M)[Math.floor(rnd()*25)];
        const mid = (female?FIRST_F:FIRST_M)[Math.floor(rnd()*25)][0];
        const sur = SUR[Math.floor(rnd()*SUR.length)];
        const birth = 1890 + Math.floor(rnd()*70);
        const death = Math.min(2025, birth + 55 + Math.floor(rnd()*40));
        const isVet = sec.kind==="veteran" ? rnd()>0.18 : rnd()>0.86;
        recs.push({
          id:++id, status, plot, section:sec, x:px, y:py, row:r, col:c, cols,
          sizeW:sec.kind==="veteran"?4:3.5, sizeL:10, notes:"",
          name:`${first} ${mid}. ${sur}`, first, sur, female,
          birth, death,
          vet: isVet ? {branch:BRANCHES[Math.floor(rnd()*BRANCHES.length)], conflict:CONFLICTS[Math.floor(rnd()*CONFLICTS.length)]} : null,
          family: sur,
          interred: `${["Mar","Apr","Jun","Aug","Sep","Nov"][Math.floor(rnd()*6)]} ${1+Math.floor(rnd()*27)}, ${death}`,
          candles: Math.floor(rnd()*180),
          tributes: Math.floor(rnd()*40),
        });
      }
    }
  }
  return recs;
}
const ALL_RECORDS = makeRecords();

/* family link counts */
const FAMILY_COUNTS = (()=>{ const m={}; ALL_RECORDS.forEach(r=>{ if(r.sur) m[r.sur]=(m[r.sur]||0)+1; }); return m; })();

const STATUS_META = {
  occupied:  {label:"Occupied",  color:"var(--brand)"},
  available: {label:"Available", color:"var(--ok)"},
  reserved:  {label:"Reserved",  color:"var(--warn)"},
  hold:      {label:"Hold",      color:"var(--hold)"},
  exhumated: {label:"Exhumated", color:"#7A6E8C"},
};

/* edit-history sample generator */
const EDITORS = ["R. Tillman","M. Okafor","Field Team","S. Brennan","Auto-import"];
function editHistory(rec){
  const rnd = mulberry32(rec.id);
  const acts = [
    "Record imported from county ledger",
    "Veteran status verified against DD‑214",
    "Headstone photo geo‑tagged",
    "Plot boundary corrected on map",
    "Family link added",
    "Interment date confirmed",
    "Memorial page published",
  ];
  const n = 2 + Math.floor(rnd()*3);
  const out=[];
  for(let i=0;i<n;i++){
    out.push({who:EDITORS[Math.floor(rnd()*EDITORS.length)], what:acts[Math.floor(rnd()*acts.length)], when:`${2021+Math.floor(rnd()*5)}‑0${1+Math.floor(rnd()*8)}‑${(10+Math.floor(rnd()*18))}`});
  }
  return out.sort((a,b)=>b.when.localeCompare(a.when));
}

/* ───── shared primitives ───── */
function Pill({status}){
  const m = STATUS_META[status]; if(!m) return null;
  return <span className="pill" style={{color:m.color, borderColor:`color-mix(in oklab, ${m.color} 32%, transparent)`}}><i className="pd"></i>{m.label}</span>;
}
function VetPill({vet, small}){
  if(!vet) return null;
  return <span className="pill vet">★ {vet.branch.replace("U.S. ","")}{small?"":` · ${vet.conflict}`}</span>;
}
function Avatar({seed=1, size=32, radius="50%"}){
  const hue = (seed*47)%40;
  return <div style={{width:size,height:size,borderRadius:radius,flex:"none",border:"1px solid var(--line)",
    background:`repeating-linear-gradient(135deg, hsl(${120+hue} 14% ${52+ (seed%3)*4}%) 0 ${size/9}px, hsl(${120+hue} 12% ${44+(seed%3)*4}%) ${size/9}px ${size/4.5}px)`}}></div>;
}
function lifespan(r){ return r.name? `${r.birth} – ${r.death}` : "—"; }
function initials(name){ return name? name.split(" ").map(s=>s[0]).slice(0,2).join("") : "—"; }

/* upcoming interments — attached to reserved records so they link to record cards */
function intermentDayText(n, time){
  const d=new Date(); d.setDate(d.getDate()+n);
  const lbl = n===0?"Today":n===1?"Tomorrow":d.toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"});
  return lbl + " · " + time;
}
const INTERMENT_PLAN = [
  {day:0, time:"11:00 AM", type:"Burial", source:"Hartwell Funeral Home", service:"Graveside service, ~30 attendees. Tent set for 10:30.", celebrant:"Pastor T. Hale"},
  {day:1, time:"10:00 AM", type:"Burial", source:"Riverside Funeral Home", service:"Full military honors. Flag detail 9:45, rifle volley.", celebrant:"Chaplain R. Wilkers"},
  {day:1, time:"2:30 PM", type:"Urn interment", source:null, service:"Immediate family only. Niche placement.", celebrant:"—"},
  {day:3, time:"9:30 AM", type:"Burial", source:"Hartwell Funeral Home", service:"Pallbearers ×6. Reception to follow off-site.", celebrant:"Rev. M. Doyle"},
  {day:5, time:"1:00 PM", type:"Urn interment", source:"Riverside Funeral Home", service:"Memorial Ridge niche. Small gathering.", celebrant:"—"},
];
(function attachInterments(){
  const reserved = ALL_RECORDS.filter(r=>r.status==="reserved" && r.name);
  INTERMENT_PLAN.forEach((p,i)=>{ const r=reserved[(i*53)%reserved.length]; if(r && !r.interment){ r.interment={...p, status:"confirmed", dateText:intermentDayText(p.day,p.time)}; } });
})();

/* expose */
Object.assign(window, {
  React, useState, useEffect, useRef, useMemo, useCallback,
  ALL_RECORDS, SECTIONS, STATUS_META, FAMILY_COUNTS, STATUSES, BRANCHES, CONFLICTS,
  Pill, VetPill, Avatar, lifespan, initials, editHistory, mulberry32, intermentDayText,
});
