/* global React, ReactDOM */
const { useState, useEffect, useRef, useMemo } = React;

// ============================================================
//  Carte Famili — Certificat d'inscription au régime de
//  couverture santé familiale — bilingual editor
//  (Original design — not affiliated with CNSS)
// ============================================================

const TWEAKS_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "teal",
  "pattern": "octagram",
  "showLogo": true,
  "showWatermark": true,
  "layout": "classic"
}/*EDITMODE-END*/;

const THEMES = {
  teal:    { ink: "oklch(0.36 0.05 200)", brand: "oklch(0.50 0.09 195)", accent: "oklch(0.72 0.10 75)",  paper: "oklch(0.985 0.012 85)", soft: "oklch(0.94 0.018 195)" },
  plum:    { ink: "oklch(0.30 0.05 320)", brand: "oklch(0.46 0.10 330)", accent: "oklch(0.74 0.10 60)",  paper: "oklch(0.985 0.010 320)", soft: "oklch(0.94 0.018 320)" },
  olive:   { ink: "oklch(0.32 0.04 130)", brand: "oklch(0.48 0.08 140)", accent: "oklch(0.72 0.10 80)",  paper: "oklch(0.985 0.012 100)", soft: "oklch(0.93 0.020 130)" },
  ink:     { ink: "oklch(0.20 0.01 250)", brand: "oklch(0.30 0.02 250)", accent: "oklch(0.70 0.13 50)",  paper: "oklch(0.985 0.005 250)", soft: "oklch(0.93 0.008 250)" },
  rose:    { ink: "oklch(0.34 0.06 20)",  brand: "oklch(0.50 0.11 20)",  accent: "oklch(0.74 0.10 60)",  paper: "oklch(0.985 0.012 30)",  soft: "oklch(0.94 0.020 20)" },
};

// Relationship options — adapt to spouse type ----------------------
const SPOUSE_OPTIONS = {
  wife:    { relAr: "الزوجة",  relFr: "Épouse"  },
  husband: { relAr: "الزوج",   relFr: "Époux"   },
  none:    { relAr: "—",       relFr: "—"        },
};
const CHILD_OPTIONS = [
  { value: "son",      relAr: "ابن",  relFr: "Fils"  },
  { value: "daughter", relAr: "ابنة", relFr: "Fille" },
];

// ---- form state ----------------------------------------------------
const initialData = {
  cardNumber: "921990126",
  cin:        "C689324",
  idcs:       "1234567890",
  lastNameLat:  "FENNICHA",
  firstNameLat: "ABDELLAZIZ",
  lastNameAr:   "فنيشة",
  firstNameAr:  "عبد العزيز",
  birthDate: "1970-02-15",
  issueDate: "2023-05-23",
  titulaireGender: "male",
  footerFr: "Conçu par Brahim Es-Sbai · Écrivain Public",
  footerAr: "من تصميم إبراهيم الصبائي · كاتب عمومي", // male => spouse is wife; female => husband
  hasSpouse: true,
  spouse: {
    nameAr: "بوبدارة حفيظة",
    id: "9159436153",
    birthDate: "1975-08-12",
  },
  children: [
    { nameAr: "فنيشة غزلان",   id: "5245986805", birthDate: "2000-04-10", kind: "daughter" },
    { nameAr: "فنيشة ابراهيم", id: "4510519488", birthDate: "2003-11-22", kind: "son" },
    { nameAr: "فنيشة معاد",    id: "8299493429", birthDate: "2007-06-03", kind: "son" },
    { nameAr: "فنيشة اية",     id: "7817893042", birthDate: "2010-09-15", kind: "daughter" },
  ],
};

// ---- helpers -------------------------------------------------------
function fmtDate(iso) {
  if (!iso) return "—";
  const [y, m, d] = iso.split("-");
  if (!y) return iso;
  return `${d}/${m}/${y}`;
}
function spaceDigits(s) { return (s || "").split("").join("\u2009"); }

function spouseRel(gender) {
  return gender === "female" ? SPOUSE_OPTIONS.husband : SPOUSE_OPTIONS.wife;
}
function childRel(kind) {
  return CHILD_OPTIONS.find(c => c.value === kind) || CHILD_OPTIONS[0];
}

// =====================================================================
//  Geometric pattern — original octagram tessellation
// =====================================================================
function PatternDefs({ id, color, kind }) {
  if (kind === "rings") {
    return (
      <defs>
        <pattern id={id} x="0" y="0" width="64" height="64" patternUnits="userSpaceOnUse">
          <circle cx="32" cy="32" r="22" fill="none" stroke={color} strokeWidth="0.7" />
          <circle cx="32" cy="32" r="14" fill="none" stroke={color} strokeWidth="0.7" />
          <circle cx="32" cy="32" r="6"  fill="none" stroke={color} strokeWidth="0.7" />
          <circle cx="0"  cy="0"  r="22" fill="none" stroke={color} strokeWidth="0.7" />
          <circle cx="64" cy="0"  r="22" fill="none" stroke={color} strokeWidth="0.7" />
          <circle cx="0"  cy="64" r="22" fill="none" stroke={color} strokeWidth="0.7" />
          <circle cx="64" cy="64" r="22" fill="none" stroke={color} strokeWidth="0.7" />
        </pattern>
      </defs>
    );
  }
  if (kind === "weave") {
    return (
      <defs>
        <pattern id={id} x="0" y="0" width="40" height="40" patternUnits="userSpaceOnUse">
          <path d="M0 20 L20 0 L40 20 L20 40 Z" fill="none" stroke={color} strokeWidth="0.6" />
          <path d="M0 0 L40 40 M40 0 L0 40" stroke={color} strokeWidth="0.4" opacity="0.5" />
        </pattern>
      </defs>
    );
  }
  if (kind === "lines") {
    return (
      <defs>
        <pattern id={id} x="0" y="0" width="14" height="14" patternUnits="userSpaceOnUse">
          <path d="M0 14 L14 0" stroke={color} strokeWidth="0.5" />
        </pattern>
      </defs>
    );
  }
  return (
    <defs>
      <pattern id={id} x="0" y="0" width="56" height="56" patternUnits="userSpaceOnUse">
        <g fill="none" stroke={color} strokeWidth="0.6">
          <path d="M28 4 L36 12 L52 12 L52 28 L60 36 L52 44 L52 52 L36 52 L28 60 L20 52 L4 52 L4 36 L-4 28 L4 20 L4 12 L20 12 Z" transform="translate(0,-4)" />
          <rect x="14" y="14" width="28" height="28" transform="rotate(45 28 28)" />
          <rect x="18" y="18" width="20" height="20" />
        </g>
      </pattern>
    </defs>
  );
}

function PatternBackground({ kind, color, opacity = 0.18 }) {
  const id = `pat-${kind}`;
  return (
    <svg className="pattern-svg" preserveAspectRatio="none">
      <PatternDefs id={id} color={color} kind={kind} />
      <rect width="100%" height="100%" fill={`url(#${id})`} opacity={opacity} />
    </svg>
  );
}

// =====================================================================
//  Original logo — three nested family shields
// =====================================================================
function CFLogo({ color, accent, size = 56 }) {
  return (
    <svg viewBox="0 0 64 64" width={size} height={size} aria-label="Carte Famili">
      <defs>
        <linearGradient id="cf-grad" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%"  stopColor={color} />
          <stop offset="100%" stopColor={accent} stopOpacity="0.85" />
        </linearGradient>
      </defs>
      <path d="M32 6 C20 10 14 18 14 30 C14 44 22 54 32 58 C42 54 50 44 50 30 C50 18 44 10 32 6 Z"
            fill="none" stroke="url(#cf-grad)" strokeWidth="2.4" />
      <path d="M32 14 C24 17 20 23 20 31 C20 41 26 48 32 51 C38 48 44 41 44 31 C44 23 40 17 32 14 Z"
            fill="none" stroke={color} strokeWidth="1.6" opacity="0.85" />
      <circle cx="32" cy="32" r="5" fill={accent} />
    </svg>
  );
}

// =====================================================================
//  COMPACT CARD — for PNG download at business card size (54×85.6mm)
//  Rendered at 600×950px (~280 DPI for crisp print)
// =====================================================================
function CardCompact({ data, theme }) {
  const t = THEMES[theme] || THEMES.teal;

  // Total family members count
  const totalCount = 1 + (data.hasSpouse ? 1 : 0) + data.children.length;

  // When totalCount >= 6, the holder + spouse info moves to the back card.
  // The recto then shows ONLY the children (or nothing if no children).
  const moveHolderToBack = totalCount >= 6;

  // The list shown on the recto under "Bénéficiaires"
  const beneficiaries = useMemo(() => {
    const list = [];

    // For 1 or 2 total: show holder (and spouse) — uses single/pair layout
    // For 3+ total: omit holder from the list (no duplication)
    // For 6+ total: also omit spouse (moved to back), show only children
    if (totalCount <= 2) {
      list.push({
        nameAr: `${data.lastNameAr} ${data.firstNameAr}`.trim(),
        id: data.idcs,
        birthDate: data.birthDate,
        relAr: "صاحب(ة) البطاقة",
      });
      if (data.hasSpouse) {
        const r = spouseRel(data.titulaireGender);
        list.push({
          nameAr: data.spouse.nameAr,
          id: data.spouse.id,
          birthDate: data.spouse.birthDate,
          relAr: r.relAr,
        });
      }
    } else if (!moveHolderToBack && data.hasSpouse) {
      // 3-5 total: show spouse but skip holder
      const r = spouseRel(data.titulaireGender);
      list.push({
        nameAr: data.spouse.nameAr,
        id: data.spouse.id,
        birthDate: data.spouse.birthDate,
        relAr: r.relAr,
      });
    }
    // For 6+ total, holder & spouse are on the back — list only children below

    data.children.forEach(c => {
      const r = childRel(c.kind);
      list.push({ nameAr: c.nameAr, id: c.id, birthDate: c.birthDate, relAr: r.relAr });
    });
    return list;
  }, [data, totalCount, moveHolderToBack]);

  return (
    <div
      className="card-compact"
      style={{
        "--ink": t.ink,
        "--brand": t.brand,
        "--accent": t.accent,
        "--paper": t.paper,
      }}
    >
      {/* Top accent bar */}
      <div className="cc-accent" />

      {/* Header — CNSS logo (left) | AMO TADAMON (center) | Morocco logo (right) */}
      <div className="cc-head">
        <img src="cnss-logo-clean.png" alt="CNSS" className="cc-logo cc-logo-side" />
        <div className="cc-brand-center">
          <div className="cc-brand-name">AMO TADAMON</div>
          <div className="cc-brand-sub-fr">Régime d&apos;assurance maladie obligatoire</div>
        </div>
        <img src="morocco-logo.png" alt="Royaume du Maroc" className="cc-logo cc-logo-side" />
      </div>

      {/* Card number */}
      <div className="cc-num-band">
        <div className="cc-num-label">N° d&apos;immatriculation · رقم التسجيل</div>
        <div className="cc-num-value">{spaceDigits(data.cardNumber || "—")}</div>
      </div>

      {/* Titulaire identity — bilingual condensed */}
      <div className="cc-identity">
        <div className="cc-identity-row">
          <span className="cc-identity-value">{data.lastNameLat} {data.firstNameLat}</span>
          <span className="cc-identity-value-ar" dir="rtl">{data.lastNameAr} {data.firstNameAr}</span>
        </div>
        <div className="cc-identity-meta">
          <div><b>CIN:</b> {data.cin || "—"}</div>
          <div><b>IDCS:</b> {data.idcs || "—"}</div>
          <div><b>Né(e):</b> {fmtDate(data.birthDate)}</div>
          <div><b>Inscrit:</b> {fmtDate(data.issueDate)}</div>
        </div>
      </div>

      {/* Beneficiaries — layout adapts to count */}
      <div className={`cc-ben cc-ben-count-${beneficiaries.length}`}>
        <div className="cc-ben-title">
          <span>Bénéficiaires · {totalCount}</span>
          <span dir="rtl">المستفيدون</span>
        </div>

        {beneficiaries.length === 1 ? (
          /* SINGLE BENEFICIARY — hero card layout */
          <div className="cc-ben-single">
            <div className="cc-ben-single-badge">
              <svg viewBox="0 0 32 32" width="34" height="34" aria-hidden="true">
                <circle cx="16" cy="16" r="15" fill="none" stroke="var(--brand)" strokeWidth="1.5" />
                <circle cx="16" cy="12" r="5" fill="var(--brand)" opacity="0.85" />
                <path d="M 6 26 Q 16 19 26 26" fill="var(--brand)" opacity="0.85" />
              </svg>
              <span className="cc-ben-single-rel" dir="rtl">{beneficiaries[0].relAr}</span>
            </div>
            <div className="cc-ben-single-name" dir="rtl">{beneficiaries[0].nameAr || "—"}</div>
            <div className="cc-ben-single-meta">
              <div className="cc-ben-single-item">
                <span className="cc-ben-single-label">IDCS</span>
                <span className="cc-ben-single-value">{beneficiaries[0].id || "—"}</span>
              </div>
              <div className="cc-ben-single-divider" />
              <div className="cc-ben-single-item">
                <span className="cc-ben-single-label">Date de naissance</span>
                <span className="cc-ben-single-value">{fmtDate(beneficiaries[0].birthDate)}</span>
              </div>
            </div>
          </div>
        ) : beneficiaries.length === 2 ? (
          /* TWO BENEFICIARIES — paired card layout */
          <div className="cc-ben-pair">
            {beneficiaries.map((b, i) => (
              <div key={i} className={`cc-ben-pair-card ${i === 0 ? "cc-ben-pair-titulaire" : ""}`}>
                <div className="cc-ben-pair-rel" dir="rtl">{b.relAr}</div>
                <div className="cc-ben-pair-name" dir="rtl">{b.nameAr || "—"}</div>
                <div className="cc-ben-pair-row">
                  <span className="cc-ben-pair-label">IDCS</span>
                  <span className="cc-ben-pair-value">{b.id || "—"}</span>
                </div>
                <div className="cc-ben-pair-row">
                  <span className="cc-ben-pair-label">Né(e)</span>
                  <span className="cc-ben-pair-value">{fmtDate(b.birthDate)}</span>
                </div>
              </div>
            ))}
          </div>
        ) : (
          /* 3-8 BENEFICIARIES — table layout (no relation column) */
          <div className="cc-ben-list" dir="rtl">
            {beneficiaries.map((b, i) => (
              <div key={i} className="cc-ben-row">
                <div className="cc-ben-num">{i + 1}</div>
                <div className="cc-ben-name">{b.nameAr || "—"}</div>
                <div className="cc-ben-id">{b.id || "—"}</div>
                <div className="cc-ben-birth">{fmtDate(b.birthDate)}</div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Footer — designer signature (editable) */}
      <div className="cc-foot">
        {data.footerFr && <span className="cc-foot-fr">{data.footerFr}</span>}
        {data.footerAr && <span className="cc-foot-ar" dir="rtl">{data.footerAr}</span>}
      </div>
    </div>
  );
}

// =====================================================================
//  CARD BACK — Verso of the business card (54×85.6mm vertical)
//  Decorative side with logos and brand name only
// =====================================================================
function CardBack({ theme, data }) {
  const t = THEMES[theme] || THEMES.teal;

  const totalCount = data ? (1 + (data.hasSpouse ? 1 : 0) + data.children.length) : 0;
  const showHolderInfo = data && totalCount >= 6;

  return (
    <div
      className="card-back"
      style={{
        "--ink": t.ink,
        "--brand": t.brand,
        "--accent": t.accent,
        "--paper": t.paper,
      }}
    >
      {/* Top accent bar */}
      <div className="cb-accent cb-accent-top" />

      {/* Decorative geometric pattern background */}
      <svg className="cb-pattern" viewBox="0 0 600 950" preserveAspectRatio="xMidYMid slice" aria-hidden="true">
        <defs>
          <pattern id="cb-octagram" x="0" y="0" width="80" height="80" patternUnits="userSpaceOnUse">
            <g fill="none" stroke="currentColor" strokeWidth="0.6" opacity="0.5">
              <path d="M 40 8 L 56 24 L 72 40 L 56 56 L 40 72 L 24 56 L 8 40 L 24 24 Z" />
              <path d="M 40 0 L 64 16 L 80 40 L 64 64 L 40 80 L 16 64 L 0 40 L 16 16 Z" />
            </g>
          </pattern>
          <radialGradient id="cb-glow" cx="50%" cy="50%" r="50%">
            <stop offset="0%" stopColor="var(--brand)" stopOpacity="0.0" />
            <stop offset="60%" stopColor="var(--brand)" stopOpacity="0.04" />
            <stop offset="100%" stopColor="var(--brand)" stopOpacity="0.10" />
          </radialGradient>
        </defs>
        <rect width="600" height="950" fill="url(#cb-octagram)" style={{ color: t.brand, opacity: 0.18 }} />
        <rect width="600" height="950" fill="url(#cb-glow)" />
      </svg>

      {/* Decorative corner ornaments */}
      <svg className="cb-corner cb-corner-tl" viewBox="0 0 80 80" aria-hidden="true">
        <g fill="none" stroke={t.accent} strokeWidth="1.5" strokeLinecap="round">
          <path d="M 5 35 L 5 5 L 35 5" />
          <path d="M 12 28 L 12 12 L 28 12" opacity="0.6" />
          <circle cx="5" cy="5" r="2" fill={t.accent} stroke="none" />
        </g>
      </svg>
      <svg className="cb-corner cb-corner-tr" viewBox="0 0 80 80" aria-hidden="true">
        <g fill="none" stroke={t.accent} strokeWidth="1.5" strokeLinecap="round">
          <path d="M 75 35 L 75 5 L 45 5" />
          <path d="M 68 28 L 68 12 L 52 12" opacity="0.6" />
          <circle cx="75" cy="5" r="2" fill={t.accent} stroke="none" />
        </g>
      </svg>
      <svg className="cb-corner cb-corner-bl" viewBox="0 0 80 80" aria-hidden="true">
        <g fill="none" stroke={t.accent} strokeWidth="1.5" strokeLinecap="round">
          <path d="M 5 45 L 5 75 L 35 75" />
          <path d="M 12 52 L 12 68 L 28 68" opacity="0.6" />
          <circle cx="5" cy="75" r="2" fill={t.accent} stroke="none" />
        </g>
      </svg>
      <svg className="cb-corner cb-corner-br" viewBox="0 0 80 80" aria-hidden="true">
        <g fill="none" stroke={t.accent} strokeWidth="1.5" strokeLinecap="round">
          <path d="M 75 45 L 75 75 L 45 75" />
          <path d="M 68 52 L 68 68 L 52 68" opacity="0.6" />
          <circle cx="75" cy="75" r="2" fill={t.accent} stroke="none" />
        </g>
      </svg>

      {/* Content */}
      <div className={`cb-content ${showHolderInfo ? "cb-content-with-holder" : ""}`}>

        {/* Morocco coat of arms — top */}
        <div className="cb-morocco">
          <img src="morocco-logo.png" alt="Royaume du Maroc" className="cb-morocco-img" />
          <div className="cb-morocco-label">
            <div className="cb-morocco-ar" dir="rtl">المملكة المغربية</div>
            <div className="cb-morocco-fr">Royaume du Maroc</div>
          </div>
        </div>

        {/* Center divider with ornament */}
        <div className="cb-divider">
          <span className="cb-divider-line" />
          <svg className="cb-divider-icon" viewBox="0 0 24 24" aria-hidden="true">
            <path d="M 12 2 L 14.5 9 L 22 9 L 16 13.5 L 18.5 21 L 12 16.5 L 5.5 21 L 8 13.5 L 2 9 L 9.5 9 Z"
                  fill="none" stroke={t.brand} strokeWidth="1.2" strokeLinejoin="round" />
          </svg>
          <span className="cb-divider-line" />
        </div>

        {showHolderInfo ? (
          /* When 6+ beneficiaries: holder + spouse info on the back */
          <div className="cb-holder-block">
            {/* Card holder */}
            <div className="cb-person cb-person-holder">
              <div className="cb-person-rel" dir="rtl">صاحب(ة) البطاقة</div>
              <div className="cb-person-name" dir="rtl">{`${data.lastNameAr} ${data.firstNameAr}`.trim() || "—"}</div>
              <div className="cb-person-name-lat">{`${data.lastNameLat} ${data.firstNameLat}`.trim()}</div>
              <div className="cb-person-meta">
                <div className="cb-person-meta-item">
                  <span className="cb-person-meta-label">IDCS</span>
                  <span className="cb-person-meta-value">{data.idcs || "—"}</span>
                </div>
                <span className="cb-person-meta-sep" />
                <div className="cb-person-meta-item">
                  <span className="cb-person-meta-label">Né(e)</span>
                  <span className="cb-person-meta-value">{fmtDate(data.birthDate)}</span>
                </div>
              </div>
            </div>

            {/* Spouse — only if hasSpouse */}
            {data.hasSpouse && (
              <div className="cb-person cb-person-spouse">
                <div className="cb-person-rel" dir="rtl">{spouseRel(data.titulaireGender).relAr}</div>
                <div className="cb-person-name" dir="rtl">{data.spouse.nameAr || "—"}</div>
                <div className="cb-person-meta">
                  <div className="cb-person-meta-item">
                    <span className="cb-person-meta-label">IDCS</span>
                    <span className="cb-person-meta-value">{data.spouse.id || "—"}</span>
                  </div>
                  <span className="cb-person-meta-sep" />
                  <div className="cb-person-meta-item">
                    <span className="cb-person-meta-label">Né(e)</span>
                    <span className="cb-person-meta-value">{fmtDate(data.spouse.birthDate)}</span>
                  </div>
                </div>
              </div>
            )}
          </div>
        ) : (
          /* Default decorative back (no holder info) */
          <div className="cb-brand">
            <div className="cb-brand-name">AMO TADAMON</div>
            <div className="cb-brand-ar" dir="rtl">آمو تضامن</div>
            <div className="cb-brand-tagline">Régime d&apos;Assurance Maladie Obligatoire</div>
            <div className="cb-brand-tagline-ar" dir="rtl">نظام التأمين الإجباري الأساسي عن المرض</div>
          </div>
        )}

        {/* Center divider */}
        <div className="cb-divider">
          <span className="cb-divider-line" />
          <svg className="cb-divider-icon" viewBox="0 0 24 24" aria-hidden="true">
            <path d="M 12 2 L 14.5 9 L 22 9 L 16 13.5 L 18.5 21 L 12 16.5 L 5.5 21 L 8 13.5 L 2 9 L 9.5 9 Z"
                  fill="none" stroke={t.brand} strokeWidth="1.2" strokeLinejoin="round" />
          </svg>
          <span className="cb-divider-line" />
        </div>

        {/* CNSS — bottom */}
        <div className="cb-cnss">
          <img src="cnss-logo-clean.png" alt="CNSS" className="cb-cnss-img" />
          <div className="cb-cnss-label">
            <div className="cb-cnss-ar" dir="rtl">الصندوق الوطني للضمان الاجتماعي</div>
            <div className="cb-cnss-fr">Caisse Nationale de Sécurité Sociale</div>
          </div>
        </div>

      </div>

      {/* Bottom accent bar */}
      <div className="cb-accent cb-accent-bottom" />
    </div>
  );
}

// =====================================================================
//  CARD
// =====================================================================
function Card({ data, theme, pattern, showLogo, showWatermark, layout }) {
  const t = THEMES[theme] || THEMES.teal;

  // Build beneficiaries list dynamically
  const beneficiaries = useMemo(() => {
    const list = [{
      nameAr: `${data.lastNameAr} ${data.firstNameAr}`.trim(),
      id: data.idcs,
      birthDate: data.birthDate,
      relAr: "صاحب(ة) البطاقة",
      relFr: "Titulaire",
    }];
    if (data.hasSpouse) {
      const r = spouseRel(data.titulaireGender);
      list.push({
        nameAr: data.spouse.nameAr,
        id: data.spouse.id,
        birthDate: data.spouse.birthDate,
        relAr: r.relAr,
        relFr: r.relFr,
      });
    }
    data.children.forEach(c => {
      const r = childRel(c.kind);
      list.push({ nameAr: c.nameAr, id: c.id, birthDate: c.birthDate, relAr: r.relAr, relFr: r.relFr });
    });
    return list;
  }, [data]);

  return (
    <div className="card-wrap">
      <div
        className={`card layout-${layout}`}
        style={{
          "--ink": t.ink,
          "--brand": t.brand,
          "--accent": t.accent,
          "--paper": t.paper,
          "--soft": t.soft,
        }}
      >
        {showWatermark && (
          <div className="card-bg">
            <PatternBackground kind={pattern} color={t.brand} opacity={0.10} />
          </div>
        )}

        <div className="ribbon ribbon-tl" />
        <div className="ribbon ribbon-br" />

        {/* Header */}
        <header className="card-head">
          <div className="head-left">
            {showLogo && (
              <div className="cnss-logo-block">
                <img
                  src="cnss-logo-clean.png"
                  alt="CNSS"
                  className="cnss-logo"
                  width="80"
                  height="40"
                />
                <div className="cnss-mark">CNSS</div>
              </div>
            )}
            <div className="brand-block">
              <div className="brand-name">AMO TADAMON</div>
              <div className="brand-sub">Régime d&apos;assurance maladie obligatoire</div>
            </div>
          </div>
          <div className="head-center">
            <div className="head-title-fr">Certificat d&apos;inscription au régime AMO</div>
            <div className="head-sub-fr">pour les personnes incapables de s&apos;acquitter des cotisations</div>
          </div>
          <div className="head-right" dir="rtl">
            <div className="head-title-ar">شهادة التسجيل</div>
            <div className="head-sub-ar">بنظام التأمين الإجباري الأساسي عن المرض</div>
            <div className="head-sub-ar-2">الخاص بالأشخاص غير القادرين على تحمل واجبات الاشتراك</div>
          </div>
        </header>

        {/* Number band */}
        <div className="number-band">
          <div className="num-label-fr">N°&nbsp;d&apos;immatriculation</div>
          <div className="num-value">{spaceDigits(data.cardNumber || "—")}</div>
          <div className="num-label-ar" dir="rtl">رقم التسجيل</div>
        </div>

        {/* Titulaire identity — Arabic on RIGHT, French on LEFT */}
        <div className="card-body">
          <section className="col col-fr">
            <Field label="Nom"               value={data.lastNameLat} />
            <Field label="Prénom"            value={data.firstNameLat} />
            <Field label="C.I.N."            value={data.cin} />
            <Field label="Date de naissance" value={fmtDate(data.birthDate)} />
            <Field label="Date d'inscription" value={fmtDate(data.issueDate)} />
          </section>

          <div className="col-divider" aria-hidden="true" />

          <section className="col col-ar" dir="rtl">
            <FieldAr label="الاسم العائلي"  value={data.lastNameAr} />
            <FieldAr label="الاسم الشخصي"  value={data.firstNameAr} />
            <FieldAr label="ب.ت.و"         value={data.cin} />
            <FieldAr label="تاريخ الازدياد" value={fmtDate(data.birthDate)} />
            <FieldAr label="تاريخ التسجيل" value={fmtDate(data.issueDate)} />
          </section>
        </div>

        {/* Beneficiaries section — improved table-style */}
        <div className="ben-section">
          <div className="ben-head">
            <span className="ben-fr">Bénéficiaires&nbsp;·&nbsp;{beneficiaries.length}</span>
            <span className="ben-rule" />
            <span className="ben-ar" dir="rtl">المستفيدون · {beneficiaries.length}</span>
          </div>

          <div className="ben-table" dir="rtl">
            <div className="ben-row ben-row-head">
              <div className="bc bc-num">#</div>
              <div className="bc bc-rel">الصلة</div>
              <div className="bc bc-name">الاسم الكامل</div>
              <div className="bc bc-birth">تاريخ الازدياد</div>
              <div className="bc bc-id">IDCS · المعرف الرقمي</div>
            </div>
            {beneficiaries.map((b, i) => (
              <div key={i} className={`ben-row ${i === 0 ? "ben-row-titulaire" : ""}`}>
                <div className="bc bc-num">{i + 1}</div>
                <div className="bc bc-rel">{b.relAr}</div>
                <div className="bc bc-name">{b.nameAr || "—"}</div>
                <div className="bc bc-birth">{fmtDate(b.birthDate)}</div>
                <div className="bc bc-id">{b.id || "—"}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Footer removed per user request */}
      </div>
    </div>
  );
}

function Field({ label, value }) {
  return (
    <div className="field field-fr">
      <div className="field-value">{value || "—"}</div>
      <div className="field-label">{label}</div>
    </div>
  );
}
function FieldAr({ label, value }) {
  return (
    <div className="field field-ar">
      <div className="field-label">{label}</div>
      <div className="field-value">{value || "—"}</div>
    </div>
  );
}

// =====================================================================
//  FORM
// =====================================================================
function Form({ data, setData }) {
  const update = (k, v) => setData({ ...data, [k]: v });
  const updateSpouse = (k, v) => setData({ ...data, spouse: { ...data.spouse, [k]: v } });

  const updateChild = (i, k, v) => {
    const children = data.children.map((c, idx) => idx === i ? { ...c, [k]: v } : c);
    setData({ ...data, children });
  };
  const addChild = () => {
    if (data.children.length >= 8) return;
    setData({ ...data, children: [...data.children, { nameAr: "", id: "", birthDate: "", kind: "son" }] });
  };
  const rmChild = (i) => setData({ ...data, children: data.children.filter((_, idx) => idx !== i) });

  const spouseLabel = data.titulaireGender === "female" ? "Époux / الزوج" : "Épouse / الزوجة";

  return (
    <div className="form">
      <FormSection title="Identité du titulaire" subtitle="بيانات صاحب(ة) البطاقة">
        <Row>
          <Input label="N° d'immatriculation" value={data.cardNumber} onChange={v => update("cardNumber", v)} />
          <Input label="C.I.N." value={data.cin} onChange={v => update("cin", v)} />
        </Row>
        <Row>
          <Input label="IDCS · المعرف الرقمي المدني والاجتماعي" value={data.idcs} onChange={v => update("idcs", v)} />
        </Row>
        <Row>
          <Input label="Nom (Latin)"    value={data.lastNameLat}  onChange={v => update("lastNameLat", v.toUpperCase())} />
          <Input label="Prénom (Latin)" value={data.firstNameLat} onChange={v => update("firstNameLat", v.toUpperCase())} />
        </Row>
        <Row>
          <Input label="الاسم العائلي" value={data.lastNameAr}  onChange={v => update("lastNameAr", v)}  rtl />
          <Input label="الاسم الشخصي" value={data.firstNameAr} onChange={v => update("firstNameAr", v)} rtl />
        </Row>
        <Row>
          <Input type="date" label="Date de naissance"  value={data.birthDate} onChange={v => update("birthDate", v)} />
          <Input type="date" label="Date d'inscription" value={data.issueDate} onChange={v => update("issueDate", v)} />
        </Row>
        <RadioGroup
          label="Sexe du titulaire / جنس صاحب البطاقة"
          value={data.titulaireGender}
          onChange={v => update("titulaireGender", v)}
          options={[
            { value: "male",   label: "Homme · ذكر" },
            { value: "female", label: "Femme · أنثى" },
          ]}
        />
      </FormSection>

      <FormSection
        title={spouseLabel}
        subtitle="بيانات القرين"
        right={
          <ToggleSwitch
            label="Inclure"
            checked={data.hasSpouse}
            onChange={v => update("hasSpouse", v)}
          />
        }
      >
        {data.hasSpouse ? (
          <>
            <Row>
              <Input label="Nom complet (AR)" value={data.spouse.nameAr} onChange={v => updateSpouse("nameAr", v)} rtl />
              <Input label="N° identifiant"   value={data.spouse.id}     onChange={v => updateSpouse("id", v)} />
            </Row>
            <Row>
              <Input type="date" label="Date de naissance / تاريخ الازدياد" value={data.spouse.birthDate} onChange={v => updateSpouse("birthDate", v)} />
            </Row>
          </>
        ) : (
          <div className="empty-note">Aucun conjoint inclus.</div>
        )}
      </FormSection>

      <FormSection
        title={`Enfants (${data.children.length}/8)`}
        subtitle="الأطفال"
        right={
          <button className="btn btn-ghost" onClick={addChild} disabled={data.children.length >= 8}>
            + Ajouter
          </button>
        }
      >
        {data.children.length === 0 && (
          <div className="empty-note">Aucun enfant ajouté.</div>
        )}
        <div className="ben-form-list">
          {data.children.map((c, i) => (
            <div key={i} className="ben-form-row">
              <div className="ben-form-num">{i + 1}</div>
              <div className="ben-form-fields">
                <Row>
                  <Input label="Nom complet (AR)" value={c.nameAr} onChange={v => updateChild(i, "nameAr", v)} rtl />
                  <Input label="N° identifiant"   value={c.id}     onChange={v => updateChild(i, "id", v)} />
                </Row>
                <Row>
                  <Input type="date" label="Date de naissance" value={c.birthDate} onChange={v => updateChild(i, "birthDate", v)} />
                  <SelectField
                    label="Sexe / الجنس"
                    value={c.kind}
                    onChange={v => updateChild(i, "kind", v)}
                    options={[
                      { value: "son",      label: "Fils · ابن"  },
                      { value: "daughter", label: "Fille · ابنة" },
                    ]}
                  />
                </Row>
              </div>
              <button className="ben-rm" onClick={() => rmChild(i)} aria-label="Supprimer">×</button>
            </div>
          ))}
        </div>
      </FormSection>

      <FormSection title="Pied de page (téléchargement)" subtitle="نص ذيل البطاقة عند التحميل">
        <Row>
          <Input
            label="Texte en français"
            value={data.footerFr}
            onChange={v => update("footerFr", v)}
          />
        </Row>
        <Row>
          <Input
            label="النص بالعربية"
            value={data.footerAr}
            onChange={v => update("footerAr", v)}
            rtl
          />
        </Row>
      </FormSection>
    </div>
  );
}

function FormSection({ title, subtitle, children, right }) {
  return (
    <section className="fsection">
      <header className="fsection-head">
        <div>
          <h3>{title}</h3>
          {subtitle && <div className="fsection-sub" dir="rtl">{subtitle}</div>}
        </div>
        {right}
      </header>
      <div className="fsection-body">{children}</div>
    </section>
  );
}

function Row({ children }) { return <div className="frow">{children}</div>; }

function Input({ label, value, onChange, type = "text", rtl }) {
  return (
    <label className={`finput ${rtl ? "rtl" : ""}`}>
      <span className="finput-label">{label}</span>
      <input
        type={type}
        value={value || ""}
        onChange={e => onChange(e.target.value)}
        dir={rtl ? "rtl" : "ltr"}
      />
    </label>
  );
}

function SelectField({ label, value, onChange, options }) {
  return (
    <label className="finput">
      <span className="finput-label">{label}</span>
      <select value={value} onChange={e => onChange(e.target.value)}>
        {options.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
      </select>
    </label>
  );
}

function RadioGroup({ label, value, onChange, options }) {
  return (
    <div className="fradio">
      <span className="finput-label">{label}</span>
      <div className="fradio-options">
        {options.map(o => (
          <label key={o.value} className={`fradio-opt ${value === o.value ? "active" : ""}`}>
            <input type="radio" checked={value === o.value} onChange={() => onChange(o.value)} />
            <span>{o.label}</span>
          </label>
        ))}
      </div>
    </div>
  );
}

function ToggleSwitch({ label, checked, onChange }) {
  return (
    <label className="ftoggle">
      <span>{label}</span>
      <input type="checkbox" checked={checked} onChange={e => onChange(e.target.checked)} />
      <span className="ftoggle-track"><span className="ftoggle-thumb" /></span>
    </label>
  );
}

// =====================================================================
//  TWEAKS
// =====================================================================
function TweaksUI({ tweaks, setTweak }) {
  const { TweaksPanel, TweakSection, TweakRadio, TweakToggle, TweakSelect } = window;
  return (
    <TweaksPanel title="Tweaks">
      <TweakSection title="Theme">
        <TweakSelect
          label="Couleur"
          value={tweaks.theme}
          onChange={v => setTweak("theme", v)}
          options={[
            { value: "teal",  label: "Teal" },
            { value: "plum",  label: "Plum" },
            { value: "olive", label: "Olive" },
            { value: "ink",   label: "Ink (mono)" },
            { value: "rose",  label: "Rose" },
          ]}
        />
        <TweakSelect
          label="Motif"
          value={tweaks.pattern}
          onChange={v => setTweak("pattern", v)}
          options={[
            { value: "octagram", label: "Octagramme" },
            { value: "weave",    label: "Tressage" },
            { value: "rings",    label: "Anneaux" },
            { value: "lines",    label: "Hachures" },
          ]}
        />
        <TweakRadio
          label="Layout"
          value={tweaks.layout}
          onChange={v => setTweak("layout", v)}
          options={[
            { value: "classic",  label: "Classique" },
            { value: "compact",  label: "Compact" },
          ]}
        />
        <TweakToggle label="Logo"      value={tweaks.showLogo}      onChange={v => setTweak("showLogo", v)} />
        <TweakToggle label="Filigrane" value={tweaks.showWatermark} onChange={v => setTweak("showWatermark", v)} />
      </TweakSection>
    </TweaksPanel>
  );
}

// =====================================================================
//  APP
// =====================================================================
function App() {
  const [data, setData] = useState(initialData);
  const [tweaks, setTweak] = window.useTweaks
    ? window.useTweaks(TWEAKS_DEFAULTS)
    : [TWEAKS_DEFAULTS, () => {}];

  const handlePrint = () => window.print();

  // Generic helper to download a card element as PNG
  const downloadCardAsPNG = async (selector, suffix) => {
    const el = document.querySelector(selector);
    if (!el) return;
    if (!window.htmlToImage) {
      alert("Bibliothèque html-to-image non chargée. Vérifiez votre connexion internet.");
      return;
    }
    try {
      const original = el.getAttribute("style") || "";
      el.setAttribute("style",
        original + "; width: 600px !important; height: 950px !important; transform: none !important;"
      );

      const dataUrl = await window.htmlToImage.toPng(el, {
        pixelRatio: 2,
        backgroundColor: "#ffffff",
        width: 600,
        height: 950,
        canvasWidth: 600,
        canvasHeight: 950,
        skipFonts: false,
        cacheBust: true,
      });

      if (original) el.setAttribute("style", original);
      else el.removeAttribute("style");

      const link = document.createElement("a");
      const fname = (data.lastNameLat || "carte") + "_" + (data.firstNameLat || "amo") + "_" + suffix + ".png";
      link.download = fname.toLowerCase().replace(/\s+/g, "_");
      link.href = dataUrl;
      link.click();
    } catch (err) {
      console.error(err);
      alert("Erreur lors du téléchargement: " + err.message);
    }
  };

  const handleDownloadPNG     = () => downloadCardAsPNG(".card-compact", "amo_recto");
  const handleDownloadBackPNG = () => downloadCardAsPNG(".card-back",    "amo_verso");

  const handleReset = () => {
    if (confirm("Effacer tous les champs ?")) {
      setData({
        cardNumber: "", cin: "", idcs: "",
        lastNameLat: "", firstNameLat: "",
        lastNameAr: "", firstNameAr: "",
        birthDate: "", issueDate: "",
        titulaireGender: "male",
        footerFr: "", footerAr: "",
        hasSpouse: false,
        spouse: { nameAr: "", id: "", birthDate: "" },
        children: [],
      });
    }
  };

  return (
    <div className="app">
      <aside className="pane pane-form" data-screen-label="Form">
        <div className="pane-head">
          <div className="brand-mini">
            <img src="cnss-logo-clean.png" alt="CNSS" width="44" height="22" />
            <div>
              <div className="pane-title">AMO TADAMON</div>
              <div className="pane-sub">Éditeur de carte d&apos;adhésion</div>
            </div>
          </div>
          <div className="pane-actions">
            <button className="btn btn-ghost" onClick={handleReset}>Effacer</button>
            <button className="btn btn-ghost" onClick={handlePrint}>Imprimer</button>
            <button className="btn btn-primary" onClick={handleDownloadPNG}>↓ Recto</button>
            <button className="btn btn-primary" onClick={handleDownloadBackPNG}>↓ Verso</button>
          </div>
        </div>
        <div className="pane-scroll">
          <Form data={data} setData={setData} />
        </div>
      </aside>

      <main className="pane pane-preview" data-screen-label="Preview">
        <div className="preview-bar">
          <div className="preview-label">Aperçu — Recto / Verso</div>
          <div className="preview-meta">{1 + (data.hasSpouse ? 1 : 0) + data.children.length} bénéficiaire(s)</div>
        </div>
        <div className="preview-stage preview-stage-cards">
          <div className="preview-card-wrap">
            <div className="preview-card-label">Recto · الوجه الأمامي</div>
            <div className="preview-card-frame">
              <CardCompact data={data} theme={tweaks.theme} />
            </div>
          </div>
          <div className="preview-card-wrap">
            <div className="preview-card-label">Verso · الوجه الخلفي</div>
            <div className="preview-card-frame">
              <CardBack theme={tweaks.theme} data={data} />
            </div>
          </div>
        </div>
      </main>

      <TweaksUI tweaks={tweaks} setTweak={setTweak} />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
