// avatars.jsx — Abstract, respectful child portrait placeholders.
// A soft warm gradient circle/squircle holds a simple iconic symbol
// (sun, kite, paper boat, butterfly, balloon, heart, leaf, star, fish, flower)
// and the child's first initial in a serif. Universal, non-realistic.

const AVATAR_PALETTES = {
  peach:  { from: "#F4D2BE", to: "#DC9A82", ink: "#5C2C1A" },
  rose:   { from: "#EFC5D2", to: "#C98AA1", ink: "#4F1E36" },
  amber:  { from: "#F0DCAA", to: "#C9974E", ink: "#5A3B12" },
  sage:   { from: "#CDDEC9", to: "#7FA284", ink: "#26452A" },
  lilac:  { from: "#DDC9E2", to: "#A487B0", ink: "#3D2643" },
  cream:  { from: "#F1E6D4", to: "#B79972", ink: "#4B361B" },
  coral:  { from: "#F4C2B6", to: "#CB7A66", ink: "#5C231A" },
  mauve:  { from: "#E1CCD3", to: "#9F7383", ink: "#46202C" },
  teal:   { from: "#C9DAD8", to: "#76998F", ink: "#1F3A35" },
};

// Symbol library — simple, iconic, friendly. Drawn in a 100x100 viewBox,
// stroke uses currentColor so we can tint with the palette's "ink".
const AvatarSymbol = ({ kind, color }) => {
  const props = { fill: "none", stroke: color, strokeWidth: 4, strokeLinecap: "round", strokeLinejoin: "round" };
  switch (kind) {
    case "sun":
      return (
        <g style={{ color }}>
          <circle cx="50" cy="50" r="14" {...props} />
          {[0,45,90,135,180,225,270,315].map(a => {
            const r1 = 22, r2 = 30;
            const rad = (a * Math.PI) / 180;
            return <line key={a} x1={50 + Math.cos(rad)*r1} y1={50 + Math.sin(rad)*r1} x2={50 + Math.cos(rad)*r2} y2={50 + Math.sin(rad)*r2} {...props} />;
          })}
        </g>
      );
    case "kite":
      return (
        <g>
          <path d="M50 22 L72 50 L50 78 L28 50 Z" {...props} />
          <line x1="50" y1="22" x2="50" y2="78" {...props} />
          <line x1="28" y1="50" x2="72" y2="50" {...props} />
          <path d="M50 78 Q46 84 52 88 Q44 90 48 96" {...props} />
        </g>
      );
    case "boat":
      return (
        <g>
          <path d="M22 60 L78 60 L66 76 L34 76 Z" {...props} />
          <path d="M50 24 L50 60" {...props} />
          <path d="M50 28 L70 56 L50 56 Z" {...props} />
        </g>
      );
    case "butterfly":
      return (
        <g>
          <path d="M50 38 C 32 24, 18 32, 22 50 C 26 66, 40 64, 50 56" {...props} />
          <path d="M50 38 C 68 24, 82 32, 78 50 C 74 66, 60 64, 50 56" {...props} />
          <path d="M50 56 C 38 70, 38 78, 50 80 C 62 78, 62 70, 50 56 Z" {...props} />
          <line x1="50" y1="36" x2="50" y2="32" {...props} />
        </g>
      );
    case "balloon":
      return (
        <g>
          <ellipse cx="50" cy="42" rx="22" ry="26" {...props} />
          <path d="M50 68 L46 72 L54 72 Z" {...props} />
          <path d="M50 72 Q44 80 52 86 Q44 90 48 96" {...props} />
        </g>
      );
    case "heart":
      return (
        <path d="M50 78 C 30 64, 18 52, 22 38 C 24 28, 36 24, 44 32 L50 38 L56 32 C 64 24, 76 28, 78 38 C 82 52, 70 64, 50 78 Z" {...props} />
      );
    case "leaf":
      return (
        <g>
          <path d="M28 76 C 28 46, 48 24, 76 24 C 76 52, 56 76, 28 76 Z" {...props} />
          <path d="M30 74 L70 30" {...props} />
        </g>
      );
    case "star":
      return (
        <path d="M50 22 L58 42 L80 44 L63 58 L68 80 L50 68 L32 80 L37 58 L20 44 L42 42 Z" {...props} />
      );
    case "fish":
      return (
        <g>
          <path d="M22 50 C 32 32, 56 32, 66 50 C 56 68, 32 68, 22 50 Z" {...props} />
          <path d="M66 50 L82 36 L82 64 Z" {...props} />
          <circle cx="32" cy="48" r="2" fill={color} stroke="none" />
        </g>
      );
    case "flower":
      return (
        <g>
          {[0,60,120,180,240,300].map(a => {
            const rad = (a * Math.PI) / 180;
            const cx = 50 + Math.cos(rad)*14;
            const cy = 50 + Math.sin(rad)*14;
            return <circle key={a} cx={cx} cy={cy} r="10" {...props} />;
          })}
          <circle cx="50" cy="50" r="6" fill={color} stroke="none" />
        </g>
      );
    case "bird":
      return (
        <g>
          <path d="M22 56 Q40 30 60 50 Q72 38 80 44 Q70 56 60 56 Q60 70 46 72 Q34 70 22 56 Z" {...props} />
          <circle cx="64" cy="46" r="1.6" fill={color} stroke="none" />
        </g>
      );
    case "moon":
      return (
        <path d="M62 26 C 46 26, 32 40, 32 56 C 32 72, 46 86, 62 86 C 50 78, 44 68, 44 56 C 44 44, 50 34, 62 26 Z" {...props} />
      );
    default:
      return null;
  }
};

// Pick a deterministic palette + symbol for a given child id/name.
const SYMBOL_KINDS = ["sun","kite","boat","butterfly","balloon","heart","leaf","star","fish","flower","bird","moon"];
const PALETTE_KEYS = Object.keys(AVATAR_PALETTES);
function hashString(s) {
  let h = 0;
  for (let i = 0; i < s.length; i++) h = ((h << 5) - h + s.charCodeAt(i)) | 0;
  return Math.abs(h);
}

// The avatar — "abstract child portrait."
function Avatar({ name = "A", seed, kind, palette, size = 80, shape = "circle", initial = true }) {
  const s = seed || name;
  const pKey = palette || PALETTE_KEYS[hashString(s) % PALETTE_KEYS.length];
  const sym = kind || SYMBOL_KINDS[hashString(s + "k") % SYMBOL_KINDS.length];
  const p = AVATAR_PALETTES[pKey];
  const radius = shape === "circle" ? "50%" : `${Math.round(size * 0.28)}px`;
  const init = (name || "").trim().charAt(0).toUpperCase();
  const gid = `g-${pKey}-${sym}-${size}`;

  return (
    <div style={{
      width: size, height: size, position: "relative",
      borderRadius: radius, overflow: "hidden",
      background: `linear-gradient(150deg, ${p.from} 0%, ${p.to} 100%)`,
      boxShadow: "inset 0 1px 0 rgba(255,255,255,0.4), inset 0 -10px 24px rgba(0,0,0,0.04)",
      flexShrink: 0,
    }}>
      {/* soft inner glow */}
      <div style={{
        position: "absolute", inset: 0, borderRadius: radius,
        background: `radial-gradient(60% 50% at 30% 20%, rgba(255,255,255,0.55), transparent 60%)`,
        pointerEvents: "none",
      }} />
      {/* Symbol */}
      <svg viewBox="0 0 100 100" width="100%" height="100%" style={{ position: "absolute", inset: 0, opacity: 0.55 }}>
        <AvatarSymbol kind={sym} color={p.ink} />
      </svg>
      {/* Initial */}
      {initial && (
        <div style={{
          position: "absolute", inset: 0, display: "flex",
          alignItems: "flex-end", justifyContent: "flex-end",
          padding: Math.max(6, size * 0.08),
          fontFamily: "var(--font-display)", fontWeight: 500,
          fontSize: Math.max(14, size * 0.22), color: p.ink,
          letterSpacing: "-0.02em", lineHeight: 1, opacity: 0.85,
        }}>{init}</div>
      )}
    </div>
  );
}

// Sample data — names are common Filipino given names. Stories are original.
// priority controls display order on both the Find a Child page and the home page.
// Lower number = shown first. The three lowest-priority campaigns appear on the home page.
// To promote a child to the home page, set their priority to 1, 2, or 3 and
// adjust the others to avoid duplicates.
const CAMPAIGNS = [
  {
    id: "ana",
    priority: 1,
    name: "Ana", age: 6, location: "Cebu City",
    need: "Heart valve repair",
    summary: "Ana was born with a hole in her heart. Surgery at PHC will let her start school in June.",
    raised: 184250, goal: 240000, days: 14,
    palette: "rose", kind: "heart",
    img: "uploads/children/children-closeup.webp",
    verified: "Verified by Philippine Heart Center, Mar 2026",
    tag: "Urgent",
    longStory: "Ana loves drawing and her younger brother. Last year, doctors found a ventricular septal defect — a small hole in her heart that tires her quickly and keeps her out of school. Her mother Marisol works as a fish vendor in Pasil; her father is a barangay tanod. The family covered the diagnostic workup, but corrective surgery is beyond what they can manage. Philippine Heart Center has scheduled the procedure for June 2 and confirmed the case for assistance. With her surgery funded, Ana can start Grade 1 in July."
  },
  {
    id: "miguel",
    priority: 2,
    name: "Miguel", age: 9, location: "Davao",
    need: "Leukemia treatment — Cycle 4",
    summary: "Miguel is halfway through his ALL protocol at SPMC. Each cycle costs US$789 / A$1,216.",
    raised: 92400, goal: 180000, days: 9,
    palette: "amber", kind: "kite",
    img: "uploads/children/children-looking-up.webp",
    verified: "Verified by Southern Phil. Medical Center",
    tag: "In treatment",
    longStory: "Miguel was diagnosed with acute lymphoblastic leukemia in November. He's a quiet boy who loves making kites from old plastic and bamboo sticks. He's now in maintenance phase and responding well — his oncologist Dr. Palacio expects remission by Cycle 6. Each cycle covers chemotherapy, bloodwork, and a 5-day inpatient stay. Funds release directly to SPMC's billing department against Miguel's case file."
  },
  {
    id: "joy",
    priority: 3,
    name: "Joy", age: 4, location: "Tacloban",
    need: "Cleft palate surgery",
    summary: "A 90-minute procedure will let Joy eat, speak, and smile clearly.",
    raised: 64500, goal: 85000, days: 21,
    palette: "peach", kind: "sun",
    img: "uploads/children/children-school-group.webp",
    verified: "Verified by Operation Smile partner clinic",
    tag: "Almost there",
  },
  {
    id: "ramon",
    priority: 4,
    name: "Ramon", age: 11, location: "Quezon City",
    need: "Kidney dialysis — 6 months",
    summary: "Ramon needs hemodialysis 3x/week while waiting for a transplant match.",
    raised: 121000, goal: 320000, days: 28,
    palette: "sage", kind: "leaf",
    img: "uploads/children/children-community-group.webp",
    verified: "Verified by National Kidney Institute",
    tag: "Long-term",
  },
  {
    id: "luz",
    priority: 5,
    name: "Luz", age: 2, location: "Iloilo",
    need: "Hearing aids (bilateral)",
    summary: "Luz lost most of her hearing after meningitis. Aids will let her learn to speak.",
    raised: 38900, goal: 64000, days: 12,
    palette: "lilac", kind: "butterfly",
    img: "test2.jpg",
    verified: "Verified by West Visayas State University Med Ctr",
    tag: "Verified",
  },
  {
    id: "ben",
    priority: 6,
    name: "Ben", age: 7, location: "Baguio",
    need: "Eye surgery — congenital cataract",
    summary: "A 30-minute outpatient procedure will give Ben usable vision in his left eye.",
    raised: 21500, goal: 48000, days: 18,
    palette: "teal", kind: "fish",
    img: "test3.jpg",
    verified: "Verified by Baguio General Hospital",
    tag: "Verified",
  },
];

// Stories of completed cases.
const STORIES = [
  {
    name: "Lia, 8", location: "Bacolod",
    title: "Six months after surgery, Lia is back in school.",
    body: "Lia's scoliosis surgery was funded in October 2025. She's now in Grade 3, swimming twice a week, and has gained 4 kg.",
    palette: "rose", kind: "star",
    funded: "US$5,000 / A$7,703 raised", outcome: "Spinal correction · Aug 2025",
  },
  {
    name: "Kiko, 5", location: "Zamboanga",
    title: "Kiko's hearing aids arrived last spring.",
    body: "His mother sends an audio message every month. His first word, three weeks in, was \"Ma.\"",
    palette: "amber", kind: "moon",
    funded: "US$1,272 / A$1,959 raised", outcome: "Bilateral hearing aids · Apr 2025",
  },
  {
    name: "Ina, 10", location: "Tagaytay",
    title: "Ina finished her last chemotherapy cycle in February.",
    body: "She's in remission. Her oncologist expects a full recovery and she's painting again — usually birds.",
    palette: "lilac", kind: "bird",
    funded: "US$5,965 / A$9,189 raised", outcome: "ALL protocol · 18 months",
  },
];

// Expose to other scripts
Object.assign(window, {
  Avatar, AvatarSymbol, AVATAR_PALETTES, CAMPAIGNS, STORIES,
  avatarSvgUrl, ChildPhoto,
});

// ─────────────────────────────────────────────────────────────
// avatarSvgUrl — render the abstract portrait as an SVG data URI.
// Used as the <image-slot src=…> fallback so dropping a real photo replaces it.
// ─────────────────────────────────────────────────────────────
function symbolSvgString(kind, color) {
  const a = (d) => `<path d="${d}" fill="none" stroke="${color}" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>`;
  switch (kind) {
    case "sun": {
      let r = `<circle cx="50" cy="50" r="14" fill="none" stroke="${color}" stroke-width="4"/>`;
      [0,45,90,135,180,225,270,315].forEach(deg => {
        const rad = deg*Math.PI/180;
        r += `<line x1="${50+Math.cos(rad)*22}" y1="${50+Math.sin(rad)*22}" x2="${50+Math.cos(rad)*30}" y2="${50+Math.sin(rad)*30}" stroke="${color}" stroke-width="4" stroke-linecap="round"/>`;
      });
      return r;
    }
    case "kite": return a("M50 22 L72 50 L50 78 L28 50 Z") + a("M50 22 L50 78") + a("M28 50 L72 50") + a("M50 78 Q46 84 52 88 Q44 90 48 96");
    case "boat": return a("M22 60 L78 60 L66 76 L34 76 Z") + a("M50 24 L50 60") + a("M50 28 L70 56 L50 56 Z");
    case "butterfly": return a("M50 38 C 32 24, 18 32, 22 50 C 26 66, 40 64, 50 56") + a("M50 38 C 68 24, 82 32, 78 50 C 74 66, 60 64, 50 56") + a("M50 56 C 38 70, 38 78, 50 80 C 62 78, 62 70, 50 56 Z") + a("M50 36 L50 32");
    case "balloon": return `<ellipse cx="50" cy="42" rx="22" ry="26" fill="none" stroke="${color}" stroke-width="4"/>` + a("M50 68 L46 72 L54 72 Z") + a("M50 72 Q44 80 52 86 Q44 90 48 96");
    case "heart": return a("M50 78 C 30 64, 18 52, 22 38 C 24 28, 36 24, 44 32 L50 38 L56 32 C 64 24, 76 28, 78 38 C 82 52, 70 64, 50 78 Z");
    case "leaf": return a("M28 76 C 28 46, 48 24, 76 24 C 76 52, 56 76, 28 76 Z") + a("M30 74 L70 30");
    case "star": return a("M50 22 L58 42 L80 44 L63 58 L68 80 L50 68 L32 80 L37 58 L20 44 L42 42 Z");
    case "fish": return a("M22 50 C 32 32, 56 32, 66 50 C 56 68, 32 68, 22 50 Z") + a("M66 50 L82 36 L82 64 Z") + `<circle cx="32" cy="48" r="2" fill="${color}"/>`;
    case "flower": {
      let r = "";
      [0,60,120,180,240,300].forEach(deg => {
        const rad = deg*Math.PI/180;
        r += `<circle cx="${50+Math.cos(rad)*14}" cy="${50+Math.sin(rad)*14}" r="10" fill="none" stroke="${color}" stroke-width="4"/>`;
      });
      r += `<circle cx="50" cy="50" r="6" fill="${color}"/>`;
      return r;
    }
    case "bird": return a("M22 56 Q40 30 60 50 Q72 38 80 44 Q70 56 60 56 Q60 70 46 72 Q34 70 22 56 Z") + `<circle cx="64" cy="46" r="1.6" fill="${color}"/>`;
    case "moon": return a("M62 26 C 46 26, 32 40, 32 56 C 32 72, 46 86, 62 86 C 50 78, 44 68, 44 56 C 44 44, 50 34, 62 26 Z");
    default: return "";
  }
}

function avatarSvgUrl({ name = "A", seed, palette, kind, size = 600, initial = true }) {
  const s = seed || name;
  const pKey = palette || PALETTE_KEYS[hashString(s) % PALETTE_KEYS.length];
  const sym = kind || SYMBOL_KINDS[hashString(s + "k") % SYMBOL_KINDS.length];
  const p = AVATAR_PALETTES[pKey];
  const init = (name || "").trim().charAt(0).toUpperCase();
  const initEl = initial ? `<text x="92" y="92" text-anchor="end" font-family="Newsreader, Georgia, serif" font-size="22" font-weight="500" fill="${p.ink}" opacity="0.85">${init}</text>` : "";
  const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="${size}" height="${size}" preserveAspectRatio="xMidYMid slice"><defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="${p.from}"/><stop offset="1" stop-color="${p.to}"/></linearGradient><radialGradient id="h" cx="0.3" cy="0.2" r="0.6"><stop offset="0" stop-color="rgba(255,255,255,0.55)"/><stop offset="0.6" stop-color="rgba(255,255,255,0)"/></radialGradient></defs><rect width="100" height="100" fill="url(#g)"/><rect width="100" height="100" fill="url(#h)"/><g opacity="0.55">${symbolSvgString(sym, p.ink)}</g>${initEl}</svg>`;
  return "data:image/svg+xml;utf8," + encodeURIComponent(svg);
}

// ─────────────────────────────────────────────────────────────
// ChildPhoto — image-slot drop zone that falls back to the abstract avatar.
// Drop a real photo onto it (with consent / signed media release) and it persists.
// ─────────────────────────────────────────────────────────────
function ChildPhoto({ name, palette, kind, slotId, shape = "rounded", radius = 0, style = {}, img }) {
  const url = img || avatarSvgUrl({ name, palette, kind, size: 600, initial: false });
  return React.createElement("image-slot", {
    id: slotId,
    src: url,
    shape,
    radius: String(radius),
    placeholder: `Drop ${name}'s photo (with consent)`,
    fit: "cover",
    style: { display: "block", width: "100%", height: "100%", ...style },
  });
}
