/* =============================================================
 * Forge Dashboard — interactive Uganda map, member dashboard, progress
 * ============================================================= */

function ForgeDashboard() {
  const [groups, setGroups] = useState([]);
  const [goal, setGoal] = useState({ current: 82, target: 1000 });
  const [selected, setSelected] = useState(null);
  const [filter, setFilter] = useState("all");
  const [loaded, setLoaded] = useState(false);

  useEffect(() => {
    Promise.all([window.cms.getForgeGroups(), window.cms.getForgeGoal()]).then(([g, goal]) => {
      setGroups(g);
      setGoal(goal);
      setLoaded(true);
    }).catch(() => setLoaded(true));
  }, []);

  const filtered = filter === "all" ? groups : groups.filter((g) => g.status === filter);
  const totalMembers = groups.reduce((s, g) => s + g.members, 0);

  return (
    <div data-screen-label="04 The Forge">
      <PageHero
        breadcrumb={[{ label: "Home", to: "home" }, { label: "The Forge" }]}
        eyebrow="The Forge"
        title="A live map of every Forge group in Uganda."
        lede="Twelve men. Weekly. For life. Find one near you, or start one where you live."
        bgImage="uploads/FATHERS ARISE MEETING-49 (1).jpg"
      />

      {/* Stat strip */}
      <section className="py-10 bg-white border-b border-navy/8">
        <div className="max-w-[1280px] mx-auto px-4 sm:px-6 grid grid-cols-2 md:grid-cols-4 gap-4">
          {[
            { label: "Active Forge groups", value: goal.current, suffix: "" },
            { label: "Men meeting weekly", value: totalMembers, suffix: "" },
            { label: "Districts engaged", value: 11, suffix: "" },
            { label: "Goal", value: goal.target, suffix: "" },
          ].map((s, i) => (
            <div key={i} className="rounded-2xl bg-paper p-5 border border-navy/8">
              <div className="font-display font-black text-3xl text-navy tabular-nums">
                <CountUp to={s.value} />{s.suffix}
              </div>
              <div className="text-[11px] uppercase tracking-widest font-display font-semibold text-ink/55 mt-1">{s.label}</div>
            </div>
          ))}
        </div>
      </section>

      {/* Map + side panel */}
      <section className="py-12">
        <div className="max-w-[1280px] mx-auto px-4 sm:px-6 grid grid-cols-1 lg:grid-cols-12 gap-6">
          <div className="lg:col-span-8">
            <div className="rounded-2xl bg-white border border-navy/8 shadow-card overflow-hidden">
              <div className="flex items-center justify-between p-4 border-b border-navy/8">
                <div className="font-display font-bold text-navy">Forge groups across Uganda</div>
                <div className="flex gap-1.5 text-xs">
                  {[["all", "All"], ["active", "Active"], ["growing", "Growing"]].map(([k, l]) => (
                    <button key={k} onClick={() => setFilter(k)}
                      className={`px-3 py-1.5 rounded-full font-display font-semibold uppercase tracking-wider ${filter === k ? "bg-navy text-white" : "bg-paper text-ink/60 hover:text-navy"}`}>
                      {l}
                    </button>
                  ))}
                </div>
              </div>
              <UgandaMap groups={filtered} selected={selected} onSelect={setSelected} loaded={loaded} />
            </div>
          </div>

          <aside className="lg:col-span-4 space-y-4">
            <div className="rounded-2xl bg-navy text-white p-6 relative overflow-hidden">
              <div className="absolute inset-0 grid-bg opacity-20" />
              <div className="relative">
                <div className="text-xs font-display font-bold uppercase tracking-widest text-gold">Goal Counter</div>
                <div className="mt-2 font-display font-black text-5xl">
                  <CountUp to={goal.current} /><span className="text-white/40 text-3xl"> / {goal.target}</span>
                </div>
                <div className="mt-3 h-2.5 rounded-full bg-white/15 overflow-hidden">
                  <div className="h-full bg-gold transition-all duration-1000" style={{ width: `${(goal.current / goal.target) * 100}%` }} />
                </div>
                <div className="mt-2 text-xs text-white/70">{((goal.current / goal.target) * 100).toFixed(1)}% of national goal</div>
                <div className="mt-5 flex gap-2 flex-wrap">
                  <Button to="get-involved" variant="gold" size="sm">Start a Forge</Button>
                  <Button to="contact" variant="ghost" size="sm">Talk to us</Button>
                </div>
              </div>
            </div>

            {selected ? (
              <ForgeDetail group={selected} onClose={() => setSelected(null)} />
            ) : (
              <div className="rounded-2xl bg-white border border-navy/8 p-6">
                <div className="text-xs font-display font-bold uppercase tracking-widest text-sky">Tip</div>
                <h3 className="mt-1 font-display font-bold text-navy">Tap a marker</h3>
                <p className="mt-1 text-sm text-ink/65">Select any Forge group on the map to see members, meeting times and how to join.</p>
              </div>
            )}

            <div className="rounded-2xl bg-white border border-navy/8 overflow-hidden">
              <div className="p-4 border-b border-navy/8 font-display font-bold text-navy">Nearby groups</div>
              <ul className="max-h-[280px] overflow-auto">
                {filtered.slice(0, 6).map((g) => (
                  <li key={g.id}>
                    <button onClick={() => setSelected(g)} className={`w-full text-left p-4 hover:bg-paper border-b border-navy/5 last:border-b-0 flex items-center justify-between ${selected?.id === g.id ? "bg-paper" : ""}`}>
                      <div>
                        <div className="font-display font-bold text-navy">{g.name}</div>
                        <div className="text-xs text-ink/55">{g.region} · {g.members} men</div>
                      </div>
                      <span className={`text-[10px] font-display font-bold uppercase tracking-widest px-2 py-0.5 rounded-full ${g.status === "active" ? "bg-sky/10 text-sky" : "bg-gold/15 text-[#A07700]"}`}>{g.status}</span>
                    </button>
                  </li>
                ))}
              </ul>
            </div>
          </aside>
        </div>
      </section>

      <MemberDashboard />
    </div>
  );
}

function ForgeDetail({ group, onClose }) {
  // Rotate through real Forge photos by group id so each Forge feels unique
  const groupPhotos = [
    "uploads/Forge 1-104.jpg",
    "uploads/forge meeting event section.jpg",
    "uploads/FATHERS ARISE MEETING-49 (1).jpg",
    "uploads/FATHERS ARISE MEETING-66.jpg",
    "uploads/FATHERS ARISE MEETING-79.jpg",
    "uploads/TRG_Father_sBreakfast125.jpg"
  ];
  const photo = groupPhotos[(group.id?.charCodeAt(0) || 0) % groupPhotos.length];
  return (
    <div className="rounded-2xl bg-white border-2 border-navy/15 shadow-cardHover overflow-hidden">
      <img src={photo} alt={`Forge ${group.region}`} className="w-full object-cover" style={{ aspectRatio: "3/2" }} />
      <div className="p-5">
        <div className="flex items-start justify-between gap-3">
          <div>
            <div className="text-[10px] font-display font-bold uppercase tracking-widest text-sky">{group.region}</div>
            <h3 className="mt-0.5 font-display font-extrabold text-xl text-navy">{group.name}</h3>
          </div>
          <button onClick={onClose} className="text-ink/40 hover:text-navy" aria-label="Close">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M6 6l12 12M6 18L18 6" stroke="currentColor" strokeWidth="2"/></svg>
          </button>
        </div>
        <dl className="mt-3 grid grid-cols-2 gap-3 text-sm">
          <div><dt className="text-xs text-ink/55">Members</dt><dd className="font-display font-bold text-navy">{group.members} men</dd></div>
          <div><dt className="text-xs text-ink/55">Meeting</dt><dd className="font-display font-bold text-navy">Tue · 7pm</dd></div>
          <div><dt className="text-xs text-ink/55">Status</dt><dd className="font-display font-bold text-navy capitalize">{group.status}</dd></div>
          <div><dt className="text-xs text-ink/55">Curriculum</dt><dd className="font-display font-bold text-navy">Be a Man · wk 7</dd></div>
        </dl>
        <div className="mt-4 flex gap-2 flex-wrap">
          <Button to="get-involved" variant="navy" size="sm">Request to join</Button>
          <Button to="contact" variant="outline" size="sm">Contact lead</Button>
        </div>
      </div>
    </div>
  );
}

/* ----- Uganda map (placeholder polygon) ----- */
function UgandaMap({ groups, selected, onSelect, loaded }) {
  // Stylised Uganda outline. Hand-drawn approximation; a real map ships from the CMS.
  const ugandaPath = "M 22 18 Q 30 12 42 14 L 58 14 Q 68 18 72 22 L 80 22 L 84 28 L 82 36 L 86 44 Q 86 52 82 58 L 78 64 Q 76 70 72 74 L 64 82 Q 54 86 44 82 L 30 80 Q 22 74 18 66 L 16 56 Q 12 48 16 40 L 18 30 Q 18 22 22 18 Z";

  return (
    <div className="relative bg-[#F0F4FB]">
      <div className="absolute top-3 left-3 right-3 z-10 flex items-center justify-between text-[10px] font-display uppercase tracking-widest text-ink/55">
        <span>Uganda · Forge network</span>
        <span className="font-mono">{groups.length} groups shown</span>
      </div>
      <svg viewBox="0 0 100 100" className="w-full h-[520px]" preserveAspectRatio="xMidYMid meet">
        {/* graticule */}
        <defs>
          <pattern id="grid-uganda" width="6" height="6" patternUnits="userSpaceOnUse">
            <path d="M 6 0 L 0 0 0 6" fill="none" stroke="#1A237E" strokeOpacity="0.05" strokeWidth="0.2" />
          </pattern>
          <linearGradient id="ug-fill" x1="0" x2="0" y1="0" y2="1">
            <stop offset="0%" stopColor="#E8EFFB" />
            <stop offset="100%" stopColor="#D2DEF1" />
          </linearGradient>
        </defs>
        <rect width="100" height="100" fill="url(#grid-uganda)" />

        {/* Uganda body */}
        <path d={ugandaPath} fill="url(#ug-fill)" stroke="#1A237E" strokeOpacity="0.35" strokeWidth="0.4" />

        {/* Lake Victoria (south-east blob) */}
        <ellipse cx="62" cy="78" rx="14" ry="6" fill="#039BE5" opacity="0.28" />
        <text x="62" y="79" fontSize="2.4" textAnchor="middle" fill="#1A237E" fillOpacity="0.5" fontFamily="Open Sans" fontStyle="italic">Lake Victoria</text>

        {/* Region label */}
        <text x="44" y="20" fontSize="2" fill="#1A237E" fillOpacity="0.4" fontFamily="Open Sans" textAnchor="middle">NORTHERN</text>
        <text x="28" y="48" fontSize="2" fill="#1A237E" fillOpacity="0.4" fontFamily="Open Sans" textAnchor="middle">WESTERN</text>
        <text x="62" y="50" fontSize="2" fill="#1A237E" fillOpacity="0.4" fontFamily="Open Sans" textAnchor="middle">EASTERN</text>
        <text x="50" y="70" fontSize="2" fill="#1A237E" fillOpacity="0.4" fontFamily="Open Sans" textAnchor="middle">CENTRAL</text>

        {/* Forge markers */}
        {loaded && groups.map((g, i) => {
          const isSel = selected?.id === g.id;
          return (
            <g key={g.id} style={{ cursor: "pointer" }} onClick={() => onSelect(g)} transform={`translate(${g.x} ${g.y})`}>
              {/* halo */}
              <circle r={isSel ? 4 : 2.4} fill={g.status === "active" ? "#039BE5" : "#FFD600"} opacity="0.25">
                <animate attributeName="r" from={isSel ? 3 : 1.8} to={isSel ? 6 : 4} dur="1.8s" repeatCount="indefinite" />
                <animate attributeName="opacity" from="0.4" to="0" dur="1.8s" repeatCount="indefinite" />
              </circle>
              <circle r={isSel ? 2.2 : 1.6} fill={g.status === "active" ? "#039BE5" : "#FFD600"} stroke="#1A237E" strokeWidth="0.4" />
              {isSel && (
                <g>
                  <rect x="2.4" y="-3" width={Math.max(g.name.length * 0.95, 18)} height="3.2" rx="0.6" fill="#1A237E" />
                  <text x="3.2" y="-0.8" fontSize="2" fill="#FFD600" fontFamily="Montserrat" fontWeight="700">{g.name}</text>
                </g>
              )}
            </g>
          );
        })}
      </svg>

      {/* Legend */}
      <div className="absolute bottom-3 left-3 right-3 flex flex-wrap items-center gap-3 text-xs">
        <span className="inline-flex items-center gap-1.5 bg-white/90 px-2 py-1 rounded-full border border-navy/10"><span className="w-2 h-2 rounded-full bg-sky" /> Active</span>
        <span className="inline-flex items-center gap-1.5 bg-white/90 px-2 py-1 rounded-full border border-navy/10"><span className="w-2 h-2 rounded-full bg-gold" /> Growing</span>
        <span className="ml-auto inline-flex items-center gap-1.5 bg-white/90 px-2 py-1 rounded-full border border-navy/10 text-ink/55 font-mono text-[10px]">map · placeholder geometry</span>
      </div>
    </div>
  );
}

/* ----- Member dashboard ----- */
function MemberDashboard() {
  const [tab, setTab] = useState("login");
  const [signedIn, setSignedIn] = useState(false);

  return (
    <section className="py-20 bg-paper">
      <div className="max-w-[1280px] mx-auto px-4 sm:px-6">
        <SectionTitle eyebrow="Member Dashboard" title="Where the work shows up." center />

        <div className="mt-12 grid grid-cols-1 lg:grid-cols-12 gap-6">
          {!signedIn ? (
            <div className="lg:col-span-5">
              <div className="rounded-2xl bg-white border border-navy/8 shadow-card overflow-hidden">
                <div className="grid grid-cols-2 border-b border-navy/8">
                  {[["login", "Sign in"], ["join", "Join a Forge"]].map(([k, l]) => (
                    <button key={k} onClick={() => setTab(k)}
                      className={`p-4 font-display font-bold uppercase text-sm tracking-wider ${tab === k ? "bg-paper text-navy" : "text-ink/50"}`}>
                      {l}
                    </button>
                  ))}
                </div>
                {tab === "login" ? (
                  <form onSubmit={(e) => { e.preventDefault(); setSignedIn(true); }} className="p-6 space-y-4">
                    <Field label="Phone or email" id="login-id"><Input id="login-id" type="text" placeholder="+256 700 245 880" required /></Field>
                    <Field label="Password" id="login-pw"><Input id="login-pw" type="password" placeholder="••••••••" required /></Field>
                    <button className="w-full btn-navy rounded-full px-6 py-3 font-display font-bold uppercase tracking-wider text-sm">Sign in</button>
                    <div className="text-center text-xs text-ink/50">Forgot? Text <span className="font-mono">FORGE</span> to <span className="font-mono">8002</span>.</div>
                  </form>
                ) : (
                  <JoinForgeForm onComplete={() => setSignedIn(true)} />
                )}
              </div>
            </div>
          ) : (
            <div className="lg:col-span-5 rounded-2xl bg-navy text-white p-6 relative overflow-hidden">
              <div className="absolute inset-0 grid-bg opacity-15" />
              <div className="relative flex items-center gap-4">
                <img src="uploads/Staff photos-1.jpg" alt="Joseph K." className="w-14 h-14 rounded-full ring-2 ring-gold object-cover" />
                <div>
                  <div className="text-xs uppercase tracking-widest text-gold font-display font-bold">Welcome</div>
                  <div className="font-display font-extrabold text-2xl">Joseph K.</div>
                  <div className="text-xs text-white/60">Forge Wakiso · Be a Man · Week 7 of 12</div>
                </div>
              </div>
              <button onClick={() => setSignedIn(false)} className="absolute top-3 right-3 text-xs text-white/60 hover:text-gold">Sign out</button>
            </div>
          )}

          <div className="lg:col-span-7 grid grid-cols-1 sm:grid-cols-2 gap-6">
            <ProgressRing label="Be a Man" value={signedIn ? 7 : 0} max={12} color="#FFD600" />
            <ProgressRing label="Nurturing Bonds" value={signedIn ? 3 : 0} max={6} color="#039BE5" />
            <StepIndicator label="Forge attendance · last 12 weeks" filled={signedIn ? 10 : 0} total={12} />
            <div className="rounded-2xl bg-white border border-navy/8 p-6">
              <div className="text-xs font-display font-bold uppercase tracking-widest text-sky">Next meeting</div>
              <div className="mt-1 font-display font-extrabold text-2xl text-navy">Tue · 7:00pm</div>
              <div className="text-sm text-ink/65 mt-1">Forge Wakiso · Pastor Mukasa's home</div>
              <ul className="mt-4 text-sm text-ink/75 space-y-1.5">
                <li className="flex items-center gap-2"><span className="w-1.5 h-1.5 rounded-full bg-gold" /> Week 8: Repentance as a daily practice</li>
                <li className="flex items-center gap-2"><span className="w-1.5 h-1.5 rounded-full bg-gold" /> Bring: your journal & a story</li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function ProgressRing({ label, value, max, color }) {
  const pct = (value / max) || 0;
  const r = 44, c = 2 * Math.PI * r;
  const [ref, inView] = useInView();
  return (
    <div ref={ref} className="rounded-2xl bg-white border border-navy/8 p-6 flex items-center gap-5">
      <div className="relative w-28 h-28">
        <svg viewBox="0 0 100 100" className="w-28 h-28 -rotate-90">
          <circle cx="50" cy="50" r={r} fill="none" stroke="#E5EAF5" strokeWidth="8" />
          <circle cx="50" cy="50" r={r} fill="none" stroke={color} strokeWidth="8" strokeLinecap="round"
            strokeDasharray={c} strokeDashoffset={inView ? c * (1 - pct) : c}
            style={{ transition: "stroke-dashoffset 1.4s cubic-bezier(.2,.7,.2,1)" }} />
        </svg>
        <div className="absolute inset-0 flex flex-col items-center justify-center">
          <div className="font-display font-black text-2xl text-navy tabular-nums">{value}<span className="text-ink/40 text-base">/{max}</span></div>
          <div className="text-[10px] uppercase tracking-widest font-display text-ink/55">weeks</div>
        </div>
      </div>
      <div>
        <div className="text-xs font-display font-bold uppercase tracking-widest text-sky">In progress</div>
        <div className="mt-1 font-display font-extrabold text-xl text-navy">{label}</div>
        <div className="text-sm text-ink/60 mt-1">{Math.round(pct * 100)}% complete</div>
      </div>
    </div>
  );
}

function StepIndicator({ label, filled, total }) {
  return (
    <div className="rounded-2xl bg-white border border-navy/8 p-6">
      <div className="text-xs font-display font-bold uppercase tracking-widest text-sky">{label}</div>
      <div className="mt-3 flex flex-wrap gap-1.5">
        {Array.from({ length: total }).map((_, i) => (
          <span key={i} className={`w-6 h-6 rounded-md flex items-center justify-center text-[10px] font-display font-bold ${i < filled ? "bg-navy text-white" : "bg-paper text-ink/40 border border-navy/8"}`}>
            {i < filled ? "✓" : i + 1}
          </span>
        ))}
      </div>
      <div className="mt-3 text-sm text-ink/60">{filled} of {total} weeks attended</div>
    </div>
  );
}

function JoinForgeForm({ onComplete }) {
  const [form, setForm] = useState({ name: "", phone: "", region: "", commit: false });
  const [err, setErr] = useState({});
  const submit = (e) => {
    e.preventDefault();
    const errs = {};
    if (!form.name.trim()) errs.name = "Required";
    if (!/^[+0-9 -]{7,}$/.test(form.phone)) errs.phone = "Enter a valid phone";
    if (!form.region) errs.region = "Pick a region";
    if (!form.commit) errs.commit = "Confirm the weekly commitment";
    setErr(errs);
    if (Object.keys(errs).length === 0) onComplete();
  };
  const set = (k) => (e) => setForm({ ...form, [k]: e.target.type === "checkbox" ? e.target.checked : e.target.value });
  return (
    <form onSubmit={submit} className="p-6 space-y-4">
      <Field label="Your name" id="jf-name" error={err.name}><Input id="jf-name" value={form.name} onChange={set("name")} placeholder="Full name" /></Field>
      <Field label="Phone (WhatsApp)" id="jf-phone" error={err.phone}><Input id="jf-phone" value={form.phone} onChange={set("phone")} placeholder="+256 …" /></Field>
      <Field label="Closest region" id="jf-region" error={err.region}>
        <Select id="jf-region" value={form.region} onChange={set("region")}>
          <option value="">Choose a region</option>
          {["Kampala", "Wakiso", "Jinja", "Mbale", "Gulu", "Lira", "Mbarara", "Kasese", "Fort Portal", "Soroti", "Entebbe", "Arua"].map((r) => <option key={r}>{r}</option>)}
        </Select>
      </Field>
      <label className="flex items-start gap-3 text-sm">
        <input type="checkbox" checked={form.commit} onChange={set("commit")} className="mt-1 accent-navy" />
        <span>I'm willing to commit to a weekly Forge meeting for at least 12 weeks. {err.commit && <span className="text-red-600 ml-2">{err.commit}</span>}</span>
      </label>
      <button className="w-full btn-gold rounded-full px-6 py-3 font-display font-bold uppercase tracking-wider text-sm">Request a Forge spot</button>
    </form>
  );
}

window.ForgeDashboard = ForgeDashboard;
