import { useState, useRef, useEffect } from "react";

// ─── Global CSS Animations ──────────────────────────────────────────────────────
function GlobalStyles(){
  return(
    <style>{`
      @keyframes floatY {
        0%,100%{transform:translateY(0px) rotate(0deg);}
        50%{transform:translateY(-14px) rotate(3deg);}
      }
      @keyframes floatY2 {
        0%,100%{transform:translateY(0px) rotate(0deg);}
        50%{transform:translateY(-10px) rotate(-4deg);}
      }
      @keyframes blobDrift {
        0%{transform:scale(1) translate(0,0);}
        33%{transform:scale(1.08) translate(12px,-8px);}
        66%{transform:scale(0.96) translate(-8px,12px);}
        100%{transform:scale(1) translate(0,0);}
      }
      @keyframes fadeUp {
        from{opacity:0;transform:translateY(20px);}
        to{opacity:1;transform:translateY(0);}
      }
      @keyframes shimmer {
        0%{background-position:-300% 0;}
        100%{background-position:300% 0;}
      }
      @keyframes gradShift {
        0%,100%{background-position:0% 50%;}
        50%{background-position:100% 50%;}
      }
      @keyframes pulse2 {
        0%,100%{box-shadow:0 0 0 0 rgba(92,45,145,0.4);}
        50%{box-shadow:0 0 0 10px rgba(92,45,145,0);}
      }
      @keyframes glowRing {
        0%,100%{box-shadow:0 0 12px 2px rgba(0,184,159,0.35);}
        50%{box-shadow:0 0 24px 6px rgba(0,184,159,0.6);}
      }
      @keyframes spin {
        from{transform:rotate(0deg);}
        to{transform:rotate(360deg);}
      }
      .mt-fade-up { animation: fadeUp 0.55s ease both; }
      .mt-fade-up-2 { animation: fadeUp 0.55s 0.12s ease both; }
      .mt-fade-up-3 { animation: fadeUp 0.55s 0.24s ease both; }
      .mt-fade-up-4 { animation: fadeUp 0.55s 0.36s ease both; }
      .mt-float { animation: floatY 4s ease-in-out infinite; }
      .mt-float2 { animation: floatY2 5.5s ease-in-out infinite; }
      .mt-blob { animation: blobDrift 9s ease-in-out infinite; }
      .mt-blob2 { animation: blobDrift 12s 2s ease-in-out infinite reverse; }
      .mt-shimmer {
        background-size:300% 100%;
        animation: shimmer 2.5s linear infinite;
      }
      .mt-pulse { animation: pulse2 2s ease-in-out infinite; }
      .mt-glow-ring { animation: glowRing 2.2s ease-in-out infinite; }
      * { box-sizing: border-box; }
      body { -webkit-font-smoothing:antialiased; }
    `}</style>
  );
}

// ─── Design Tokens ─────────────────────────────────────────────────────────────
const C = {
  // Core brand — Electric Violet + Sky Blue refresh
  purple:"#7C3AED",purpleL:"#A78BFA",purpleFg:"#EDE9FE",
  mint:"#0EA5E9",mintL:"#E0F2FE",
  coral:"#F43F5E",coralL:"#FFF1F2",
  marigold:"#F59E0B",marigoldL:"#FFFBEB",
  crimson:"#DC2626",crimsonL:"#FEF2F2",crimsonM:"#EF4444",
  // Extended accent palette
  indigo:"#6366F1",indigoL:"#EEF2FF",
  rose:"#FB7185",roseL:"#FFF1F2",
  amber:"#F59E0B",amberL:"#FFFBEB",
  emerald:"#10B981",emeraldL:"#ECFDF5",
  sky:"#0EA5E9",skyL:"#E0F2FE",
  // Surface — crisp, clean
  surface:"#F8FAFC",card:"#FFFFFF",
  text:"#0F172A",muted:"#64748B",border:"#E2E8F0",
  // Shadow scale
  shadowSm:"0 1px 3px rgba(0,0,0,0.07)",
  shadowMd:"0 4px 16px rgba(0,0,0,0.08)",
  shadowLg:"0 8px 32px rgba(0,0,0,0.12)",
};
const G = {
  purple:      `linear-gradient(135deg, #7C3AED 0%, #A78BFA 100%)`,
  purpleDark:  `linear-gradient(135deg, #4C1D95 0%, #7C3AED 100%)`,
  purpleVibrant:`linear-gradient(135deg, #7C3AED 0%, #C084FC 100%)`,
  mint:        `linear-gradient(135deg, #0284C7 0%, #0EA5E9 100%)`,
  coral:       `linear-gradient(135deg, #E11D48 0%, #F43F5E 100%)`,
  marigold:    `linear-gradient(135deg, #D97706 0%, #F59E0B 100%)`,
  indigo:      `linear-gradient(135deg, #4F46E5 0%, #6366F1 100%)`,
  rose:        `linear-gradient(135deg, #E11D48 0%, #FB7185 100%)`,
  hero:        `linear-gradient(145deg, #0D0420 0%, #2E1065 35%, #7C3AED 65%, #0EA5E9 100%)`,
  card:        `linear-gradient(145deg, rgba(255,255,255,0.18), rgba(255,255,255,0.06))`,
  surface:     `linear-gradient(180deg, #F8FAFC 0%, #F1F5F9 100%)`,
  // Per-tab accent gradients
  tabFeed:      `linear-gradient(135deg,#7C3AED,#A78BFA)`,
  tabEvents:    `linear-gradient(135deg,#4F46E5,#818CF8)`,
  tabCommunity: `linear-gradient(135deg,#D97706,#F59E0B)`,
  tabMessages:  `linear-gradient(135deg,#0284C7,#0EA5E9)`,
  tabProfile:   `linear-gradient(135deg,#E11D48,#F43F5E)`,
};
const CM_AREAS = [
  { id:"ep1", label:"EC Phase 1", pin:"560100" },
  { id:"ep2", label:"EC Phase 2", pin:"560100" },
  { id:"nn",  label:"Neeladri Nagar", pin:"560100" },
  { id:"bb",  label:"Bommasandra", pin:"560099" },
];
const CURRENT_MANAGERS = {
  ep1: { name:"Suresh Babu", apt:"GM Infinite E-City Town", since:"Jan 2025", avatar:"SB", color:"#5C2D91", events:14, posts:87 },
  ep2: null,
  nn:  { name:"Divya Menon", apt:"Celebrity Paradise", since:"Mar 2025", avatar:"DM", color:"#00B89F", events:9, posts:62 },
  bb:  null,
};
const CANDIDATES_BY_AREA = {
  ep1: [],   // current manager exists, no active election
  ep2: [
    { id:1, name:"Rajesh Kumar",  apt:"Shriram Liberty Square Ph2", eventsOrg:8, posts:34, votes:142, avatar:"RK", color:"#5C2D91", profession:"Software Engineer, Wipro",  statement:"I want to make EC Phase 2 cleaner, safer and more connected for every family here." },
    { id:2, name:"Priya Sharma",  apt:"Mahaveer Ranches",            eventsOrg:6, posts:51, votes:98,  avatar:"PS", color:"#00B89F", profession:"Senior Doctor, Narayana HC",statement:"Community health awareness drives and weekend events for kids and seniors." },
    { id:3, name:"Arun Nair",     apt:"Ittina Mahavir",              eventsOrg:7, posts:22, votes:76,  avatar:"AN", color:"#FF6B7A", profession:"School Principal",           statement:"Focus on youth programs, sports days and clean neighbourhood initiatives." },
    { id:4, name:"Meenakshi Iyer",apt:"SV Grandur",                  eventsOrg:5, posts:18, votes:44,  avatar:"MI", color:"#FFB347", profession:"HR Manager, Infosys",        statement:"Better resident communication and faster issue resolution for everyone." },
  ],
  nn: [],
  bb: [
    { id:5, name:"Karthik Reddy", apt:"Ozone Urbana",                eventsOrg:6, posts:29, votes:61,  avatar:"KR", color:"#6B7FF0", profession:"Civil Engineer",             statement:"Infrastructure, roads and parking solutions are my top priority." },
    { id:6, name:"Anjali Singh",  apt:"RK Township",                 eventsOrg:5, posts:41, votes:37,  avatar:"AS", color:"#FF6B7A", profession:"Teacher, DPS",               statement:"Cultural events, festivals and bringing neighbours together." },
  ],
};
const ELECTION_DEADLINE = { ep2:"15 Mar 2026", bb:"20 Mar 2026" };
// Logged-in user mock stats
const MY_STATS = { eventsOrg:7, posts:24, area:"ep2", apt:"Shriram Liberty Square Ph2", verified:true };

// ── 6-Month Election Cycle Data ──────────────────────────────────────────────
// Phases: "stable" | "pre_election" (≤30 days, apply open) | "voting" (top-4 live) | "no_admin"
const ELECTION_PHASES = {
  ep1:"stable", ep2:"voting", nn:"pre_election", bb:"no_admin",
};
const TERM_DATA = {
  ep1:{ managerName:"Suresh Babu", termStart:"1 Jan 2026", termEnd:"1 Jul 2026",
        daysElapsed:61, totalDays:181, daysLeft:120, nextElectionOpen:"1 Jun 2026" },
  ep2:{ votingStart:"1 Mar 2026", votingEnd:"15 Mar 2026", daysLeftVoting:13,
        applyStart:"1 Feb 2026", applyEnd:"28 Feb 2026",
        totalApplicants:6, shortlistedTo:4 },
  nn: { managerName:"Divya Menon", termStart:"1 Sep 2025", termEnd:"1 Mar 2026",
        daysElapsed:182, totalDays:182, daysLeft:0,
        applyDeadline:"14 Mar 2026", applicantsCount:3, slotsLeft:1 },
  bb: { note:"No community admin elected yet. Start an election for your area!" },
};
// Applicant pool for EP2 — 6 applied, top 4 by activity score shortlisted for voting
const EP2_POOL = [
  { name:"Rajesh Kumar",  eventsOrg:8, posts:34, score:58, shortlisted:true  },
  { name:"Priya Sharma",  eventsOrg:6, posts:51, score:69, shortlisted:true  },
  { name:"Arun Nair",     eventsOrg:7, posts:22, score:43, shortlisted:true  },
  { name:"Meenakshi Iyer",eventsOrg:5, posts:18, score:33, shortlisted:true  },
  { name:"Vikram Patel",  eventsOrg:5, posts:11, score:26, shortlisted:false },
  { name:"Sunita Das",    eventsOrg:5, posts: 9, score:24, shortlisted:false },
];
// Scoring rule: (events × 3) + posts
const calcScore = (e,p) => e*3 + p;

// ─── PII Detection Engine ─────────────────────────────────────────────────────
const PII_REGEX = {
  card:  /\b\d{4}[\s\-]?\d{4}[\s\-]?\d{4}[\s\-]?\d{4}\b/,
  cvv:   /\b(cvv|cvc|security\s*code)\b/i,
  upi:   /[a-zA-Z0-9.\-_]+@(upi|paytm|gpay|phonepe|ybl|oksbi|okaxis|okhdfcbank)\b/i,
  bank:  /\b(account\s*(no|number)|ifsc|[A-Z]{4}0[A-Z0-9]{6})\b|\b\d{11,18}\b/i,
  phone: /(\+91[\s\-]?)?[6-9]\d{9}\b/,
};
const PII_META = {
  card:  { icon:"💳", label:"credit / debit card number",  msg:"Card numbers are highly sensitive payment credentials." },
  cvv:   { icon:"🔐", label:"CVV / security code",         msg:"CVV codes must never be shared — this is critical payment security." },
  upi:   { icon:"💸", label:"UPI payment ID",              msg:"UPI IDs enable direct money transfers to your account." },
  bank:  { icon:"🏦", label:"bank account information",    msg:"Bank details can be misused for unauthorised transactions." },
  phone: { icon:"📞", label:"phone number",                msg:"Phone numbers shared publicly can attract spam or harassment." },
};
function detectPII(text){ for(const [t,rx] of Object.entries(PII_REGEX)){if(rx.test(text))return t;} return null; }

// ─── Content Moderation ──────────────────────────────────────────────────────
const POLICY_TERMS=["nude","naked","porn","pornography","xxx","explicit adult","sexual content","nsfw","obscene","adult video","sex video","inappropriate image"];
function checkViolation(text){ const l=text.toLowerCase(); return POLICY_TERMS.some(k=>l.includes(k)); }

// ─── Reactions & Cross-Share Data ────────────────────────────────────────────
const REACTIONS=[
  {id:"like",  emoji:"👍",label:"Like"},   {id:"heart",emoji:"❤️",label:"Love"},
  {id:"haha",  emoji:"😂",label:"Haha"},   {id:"sad",  emoji:"😢",label:"Sad"},
  {id:"cry",   emoji:"😭",label:"Crying"}, {id:"wow",  emoji:"😮",label:"Wow"},
  {id:"angry", emoji:"😡",label:"Angry"},  {id:"thanks",emoji:"🙏",label:"Thanks"},
  {id:"cheer", emoji:"🎉",label:"Cheer"},
];
const POST_RXNS={
  8:{like:0, heart:0, sad:31,cry:44, wow:9,  angry:2, thanks:7},  // Missing Person – mostly sad/crying
  1:{like:23,heart:8, sad:2, cry:2,  wow:5,  angry:0, thanks:9},
  2:{like:14,heart:41,sad:3, cry:0,  wow:7,  angry:0, thanks:12},
  3:{like:57,heart:29,sad:0, cry:0,  wow:4,  angry:0, thanks:18},
  4:{like:19,heart:5, sad:0, cry:0,  wow:2,  angry:1, thanks:14},
  5:{like:83,heart:11,sad:4, cry:1,  wow:9,  angry:0, thanks:22},
  6:{like:8, heart:2, sad:5, cry:3,  wow:11, angry:4, thanks:3},
  7:{like:5, heart:1, sad:8, cry:2,  wow:3,  angry:0, thanks:4},
};
const NEARBY_AREAS=["Electronic City Phase 1","Neeladri Nagar","Hebbagodi","Bommasandra","Veerasandra","Chandapura","Doddathogur"];
const ALERT_CATEGORIES=["Safety","Lost & Found","Missing Person"];

// ─── Community Members mock data ─────────────────────────────────────────────
const COMMUNITY_MEMBERS=[
  {id:1,name:"Rajesh Kumar",   apt:"Shriram Liberty Square Ph2",av:"RK",avC:"#5C2D91"},
  {id:2,name:"Priya Sharma",   apt:"Mahaveer Ranches",          av:"PS",avC:"#00B89F"},
  {id:3,name:"Arun Nair",      apt:"Ittina Mahavir",            av:"AN",avC:"#FF6B7A"},
  {id:4,name:"Meenakshi Iyer", apt:"SV Grandur",                av:"MI",avC:"#FFB347"},
  {id:5,name:"Vikram Patel",   apt:"Ozone Urbana",              av:"VP",avC:"#6B7FF0"},
  {id:6,name:"Anjali Singh",   apt:"RK Township",               av:"AS",avC:"#FF6B7A"},
  {id:7,name:"Karthik Reddy",  apt:"Prestige Sunrise Park",     av:"KR",avC:"#5C2D91"},
  {id:8,name:"Sunita Das",     apt:"Celebrity Paradise",        av:"SD",avC:"#00B89F"},
];

const CAT_META = {
  "Missing Person":{icon:"🆘",color:"#B91C1C",urgent:true},
  "Safety":        {icon:"🛡️",color:"#FF6B7A"},
  "Lost & Found":  {icon:"🔍",color:"#FFB347"},
  "Services":      {icon:"🔧",color:"#5C2D91"},
  "Recommendation":{icon:"⭐",color:"#00B89F"},
  "General":       {icon:"💬",color:"#6B7FF0"},
};

// ─── Mock current user (verified=false → pending admin review) ───────────────
const MOCK_USER = {
  name:"Meena T.", apt:"Prestige Sunrise Park", area:"EC Phase 2",
  av:"MT", avC:C.purple,
  verified:true,           // set true after admin approves account
  pendingReview:false,
  role:"admin",            // "admin" | "moderator" | "resident"
};
// Categories that block unverified users completely
const NEEDS_VERIFIED_CATS = ["Services","Recommendation","General"];
// Categories allowed for unverified but go to admin review queue
const REVIEW_QUEUE_CATS   = ["Safety","Lost & Found","Missing Person"];

// ─── Validation Helpers ───────────────────────────────────────────────────────
// Allowed character sets
const RE_NAME    = /^[a-zA-Z\s.\-']+$/;           // names: letters, space, dot, hyphen, apostrophe
const RE_PHONE   = /^[\d\s\-()+]+$/;               // phone: digits + formatting chars
const RE_ADDR    = /^[a-zA-Z0-9\s,.\-\/]+$/;       // address fields: alphanumeric + , . - / space
const RE_FLAT    = RE_ADDR;                          // flat/door same as address

// ── Character STRIP functions — call on every keystroke to block invalid chars ──
const stripName  = v => v.replace(/[^a-zA-Z\s.\-']/g, "");       // names only
const stripPhone = v => v.replace(/[^0-9\s\-()+]/g, "");          // phone digits+format
const stripAddr  = v => v.replace(/[^a-zA-Z0-9\s,.\-\/]/g, "");  // address/area/apt/flat

const _hasVowel = s => /[aeiouAEIOU]/.test(s);
const _vowelRatio = s => {
  const l = s.replace(/[^a-zA-Z]/g,"");
  if(!l.length) return 1;
  return ((l.match(/[aeiouAEIOU]/g)||[]).length) / l.length;
};

const vName = v => {
  const s = v.trim();
  if(!s) return "Name is required";
  if(/\d/.test(s)) return "Name cannot contain numbers";
  if(!RE_NAME.test(s)) return "Only letters, spaces, dots and hyphens allowed";
  if(!_hasVowel(s)) return "Please enter a valid name";
  if(s.replace(/\s/g,"").length > 4 && _vowelRatio(s) < 0.12) return "Please enter a valid name";
  if(s.length < 2) return "Too short";
  return null;
};
const vPhone = v => {
  const d = v.replace(/[\s\-()]/g,"");
  if(!d) return "Mobile number is required";
  if(!/^\d+$/.test(d)) return "Numbers only — no letters or symbols";
  if(d.length !== 10) return "Must be exactly 10 digits";
  if(!/^[6-9]/.test(d)) return "Must start with 6, 7, 8 or 9";
  return null;
};
const vArea = v => {
  // Strip parenthetical annotations added by dropdown (e.g. "(PIN: 560100)")
  const clean = v.replace(/\s*\([^)]*\)/g,"").trim();
  if(!clean) return "Area is required";
  if(!RE_ADDR.test(clean)) return "Only letters, numbers, spaces, comma, dot, - and / allowed";
  return null;
};
const vApt = v => {
  const clean = v.replace(/\s*\([^)]*\)/g,"").trim();
  if(!clean) return "Apartment name is required";
  if(!RE_ADDR.test(clean)) return "Only letters, numbers, spaces, comma, dot, - and / allowed";
  if(clean.length < 3) return "Too short";
  if(/^\d+$/.test(clean)) return "Please enter a valid apartment name";
  return null;
};
const vFlat = v => {
  if(!v.trim()) return "Flat/Door number is required";
  if(!RE_ADDR.test(v)) return "Only letters, numbers, spaces, comma, dot, - and / allowed";
  return null;
};
const vBizName = v => {
  if(!v.trim()) return "Business name is required";
  if(!RE_ADDR.test(v)) return "Only letters, numbers, spaces, comma, dot, - and / allowed";
  if(v.trim().length < 2) return "Too short";
  if(/^[^a-zA-Z0-9]/.test(v.trim())) return "Must start with a letter or number";
  return null;
};
const vOwnerName = v => vName(v);   // same rules as personal name
const RE_EMAIL   = /^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$/;
const stripEmail = v => v.replace(/[^a-zA-Z0-9@._+\-]/g,"");
const vEmail = v => {
  const s = v.trim();
  if(!s) return "Email address is required";
  if(!RE_EMAIL.test(s)) return "Enter a valid email address (e.g. name@gmail.com)";
  return null;
};
const vPassword = v => {
  if(!v) return "Password is required";
  if(v.length < 6) return "Password must be at least 6 characters";
  return null;
};

// ─── All local data ─────────────────────────────────────────────────────────────
const AREA_NAMES = [
  // ── Electronic City Phase 1 & its sub-localities ──
  "Electronic City Phase 1 (PIN: 560100)",
  "Gollahalli (PIN: 560100)",
  "Shikaripalya (PIN: 560100)",
  "Neotown, EC Phase 1 (PIN: 560100)",
  "Doddathogur (PIN: 560100)",
  "Neeladri Nagar (PIN: 560100)",
  "Veerasandra (PIN: 560100)",
  // ── Electronic City Phase 2 & its sub-localities ──
  "Electronic City Phase 2 (PIN: 560100)",
  "Shanthipura, EC Phase 2 (PIN: 560100)",
  "BTM Phase 1, EC Phase 2 (PIN: 560100)",
  "Konappana Agrahara (PIN: 560100)",
  "Ananth Nagar, EC Phase 2 (PIN: 560100)",
  "Doddanagamangala (PIN: 560100)",
  "Kammasandra (PIN: 560100)",
  // ── Surrounding areas ──
  "Huskur Road Area (PIN: 560100)",
  "Hebbagodi (PIN: 560099)",
  "Bommasandra (PIN: 560099)",
  "Chandapura (PIN: 562106)",
  "Kudlu (PIN: 560068)",
];
// Grouped version of AREA_NAMES — used by SmartInput groupedOptions prop
const AREA_GROUPS = [
  { group:"EC Phase 1 & Sub-localities", icon:"🏙️", items:[
    "Electronic City Phase 1 (PIN: 560100)",
    "Gollahalli (PIN: 560100)",
    "Shikaripalya (PIN: 560100)",
    "Neotown, EC Phase 1 (PIN: 560100)",
    "Doddathogur (PIN: 560100)",
    "Neeladri Nagar (PIN: 560100)",
    "Veerasandra (PIN: 560100)",
  ]},
  { group:"EC Phase 2 & Sub-localities", icon:"🏢", items:[
    "Electronic City Phase 2 (PIN: 560100)",
    "Shanthipura, EC Phase 2 (PIN: 560100)",
    "BTM Phase 1, EC Phase 2 (PIN: 560100)",
    "Konappana Agrahara (PIN: 560100)",
    "Ananth Nagar, EC Phase 2 (PIN: 560100)",
    "Doddanagamangala (PIN: 560100)",
    "Kammasandra (PIN: 560100)",
  ]},
  { group:"Surrounding Areas", icon:"🗺️", items:[
    "Huskur Road Area (PIN: 560100)",
    "Hebbagodi (PIN: 560099)",
    "Bommasandra (PIN: 560099)",
    "Chandapura (PIN: 562106)",
    "Kudlu (PIN: 560068)",
  ]},
];
const APT_BY_AREA = {
  "Electronic City Phase 1":[
    // A
    "Ajmera Infinity","Ajmera Stone Park","Ajmera Annex",
    "Akshaya Residency","Alps Pleasanton","Amethyst Central Serviced Apartments",
    "Apple Residency","Aristo Marvel","Aashrayam Apartments",
    // C
    "Celebrity Signature","Concorde Manhattans","Concorde Tech Turf",
    "Countryside Raindance",
    // D
    "DS Max Sigma","DS-Max Starry","DS Max Star Nest",
    // G
    "GM Infinite E-City Town Phase 1","GM Infinite Smondo",
    "Godrej E-City","Godrej Nurture","Golden Abode","Gopalan Lakefront",
    // H
    "Hamsa Residency","Happy Homes 2",
    // I–K
    "Ittina Mahaveer Apartments","Keerthi Royal Palms","Keya The Lake Terraces",
    "Kolte Patil iTowers Exente",
    // M
    "Mahendra Aarna","Manya Elite","Manya Hi-Living",
    "My Fortune Apartments","My Nivas",
    // N–O
    "Neeladri Castle Apartment","Neo Elite Apartments","Nest Apartment",
    "Oakstone Paradise Apartment","Omkar Nivas - Luxury Apartments",
    // P
    "Patel Smondo 2","Patel Townsville","Pragathi Royale II","Pragna Uptown",
    "Prestige Norwood","Prestige Sunrise Park","Prestige Tanglewood",
    "PSR Krish Kamal",
    // R
    "Ramky One Karnival","Rangashree Residency","Royal Apartment",
    // S
    "Shriram Liberty Square","Shriram Signiaa","Shriram Summit",
    "SJR Equinox Apartment","SJR Fiesta Homes","SLV Elite","SNN Raj GreenBay",
    // T
    "The Green Terraces","The Lake View Address",
  ],
  "Electronic City Phase 2":[
    // A
    "Ajmera Nucleus","Amaravathi Icon","Aswani Aaeesha",
    // B
    "BASH Enclave","Bhagya Nilayam","Bren Woods","Brons Apartment",
    // C
    "Columbia Aaltius","Concorde Wind Rush",
    // E–G
    "Elegance Elite","Gopalan Lakefront",
    // I
    "Icon Happy Living","Inspira Tropical Garden","Ittina Mahavir",
    // J–K
    "JK Residency","Kaveri Pebbles",
    // M
    "Mahaveer Edenfield","Mahaveer Ranches","Mahendra Aarya",
    // P
    "Pavani Chandana","Pragathi Amber","Prakruthi Solitaire",
    "Prabhavathi Meadows","Pramuk Aqua Heights","Purnima Elite",
    // R
    "Royal Apartment",
    // S
    "Salarpuria Sattva","Shanders Dwellington","Shanders Enclave","Shanders South City",
    "Shriram Liberty Square Phase 2",
    "SJR Fiesta Homes","SNN Raj Greenbay","Sree Devi Nilayam",
    "Sri Sai Meadows","Sri Vishnu Pearls Apartment","SRS Pranav","Surbacon Cedar","SUVRITH SHELTER",
    "SV Grandur",
    // T
    "Tarika Mansion",
    // V
    "Vijay Nest",
  ],
  // ── EC Phase 1 sub-localities ──
  "Gollahalli":[
    "Countryside Raindance","DS Max Sigma","Gopalan Lakefront",
    "Rangashree Residency","Shriram Summit","The Lake View Address",
  ],
  "Shikaripalya":[
    "Concorde Tech Turf","Godrej Nurture","Keya The Lake Terraces",
  ],
  "Neotown, EC Phase 1":[
    "GM Infinite E-City Town Phase 1","GM Infinite Smondo",
    "Ramky One Karnival","The Green Terraces",
  ],
  "Neeladri Nagar":[
    "Celebrity Paradise","Celebrity Signature","DSR Sunrise",
    "MANYA ELITE","Manya Hi-Living","Omkar Nivas - Luxury Apartments",
    "Paradise Residency","Pragna Uptown","PSR Krish Kamal",
    "SLV Apartment","SLV Elite","Vaishnavi Terraces",
  ],
  "Doddathogur":[
    "Alps Pleasanton","Godrej E-City","Hamsa Residency",
    "Neo Elite Apartments","Prestige Sunrise Park",
    "Pristine Temple Bells","Purva Fountain Square",
    "Sai Ashraya Layout","Temple Bells Premier",
  ],
  "Veerasandra":[
    "Columbia Aaltius","Gopalan Lakefront","Sai Brindavan Apartments",
    "Silicon Ozone","Sri Tirumala Splendor",
  ],
  // ── EC Phase 2 sub-localities ──
  "Shanthipura, EC Phase 2": [
    "GPR Royale Layout","Sai Sarana Layout","Shanthipura Apartments",
    "Ecity Luxury Stay","Royal Guest House","Huskur Gate Residency",
  ],
  "BTM Phase 1, EC Phase 2": [
    "BTM Phase 1 Residency","Ananda Reddy Layout","Tech Mahindra Back Gate Layout",
    "Shivam Residency","Precision Compaid Building",
  ],
  "Konappana Agrahara":[
    "Aswani Aaeesha","Kolte Patil iTowers Exente",
    "SNN Raj Greenbay","SV Grandur","Vijay Nest",
  ],
  "Ananth Nagar, EC Phase 2":[
    "Ajmera Nucleus","Amaravathi Icon","Elegance Elite",
    "Pragathi Amber","Vijay Nest",
  ],
  "Doddanagamangala":[
    "Bren Woods","Brons Apartment","Shanders Dwellington",
    "Shanders Enclave","Shanders South City","SJR Fiesta Homes",
  ],
  "Kammasandra":[
    "Inspira Tropical Garden","Mahendra Aarya","Purnima Elite",
    "Sri Vishnu Pearls Apartment",
  ],
  // ── Surrounding areas ──
  "Huskur Road Area":["Salarpuria Sattva Greenage","Radiant Heritage","BEML Layout Residences"],
  "Bommasandra":["Habulus Samruddi","RK Township","Pristine Residency","Ozone Urbana"],
  "Chandapura":["JR Habitat","Nayana Greens","Aswani Sitara","My Home Bhooja"],
  "Hebbagodi":["Hebbagodi Layout","Adarsh Welkin Park","Godrej Ananda","Shriram Summitt"],
  "Kudlu":["Kudlu Gate Layout","SNN Mark","Adarsh Palm Retreat","Provident Kenworth"],
};
const ALL_APTS = Object.values(APT_BY_AREA).flat();
const STREETS = [
  // National Highways
  "Hosur Road (NH 44)","Outer Ring Road (NH 275)","NH 75",
  // Major roads
  "Neeladri Road","Veerasandra Road",
  "Gollahalli Main Road","Shikaripalya Main Road","Kammasandra Main Road",
  "Doddathogur Main Road","Doddanagamangala Road","Huskur Road",
  "Shanthi Pura Main Road","ITC 5 Path (Doddanagamangala)",
  "Veerasandra Main Road, EC Phase 2","BTM Phase 1 Road",
  "Anantha Nagar Road, Kammasandra","GPR Royale Layout Road",
  "Konappana Agrahara Main Road","Hebbagodi Main Road","Bommasandra Ring Road",
  "Velankani Drive","Neotown Main Road","Smondoville Road",
  "Electronic City Elevated Expressway","Electronic City Service Road",
  "Jigani Road","Chandapura–Anekal Road","NICE Road","Sarjapur Road",
  "Gollahalli–Electronic City Road",
  // Campus / institution avenues (official names)
  "Infosys Avenue","Hewlett Packard Avenue",
  "Bangalore Bioinnovation Centre Road","Symbiosis–CGI Road",
  "Abbaiah Reddy Street","Lotus Path",
  "Infosys Gate Road","Wipro Gate Road (Gate 13)",
  // Numbered roads — Phase 1
  "1st Cross, EC Phase 1","2nd Cross, EC Phase 1","3rd Cross, EC Phase 1",
  "4th Cross Road, EC Phase 1","5th Cross Road, EC Phase 1",
  "6th Cross Road, EC Phase 1","11th Cross Road, EC Phase 1",
  "12th Cross Road, EC Phase 1","13th Cross Road, EC Phase 1",
  "16th Cross Road, EC Phase 1",
  // Numbered roads — Phase 2
  "1st Main Road, EC Phase 2","2nd Main Road, EC Phase 2",
  "4th Main Road, EC Phase 2","9th Cross Road, EC Phase 2",
  // Local streets
  "Bachappa Road","Veerasandra Main Road",
];
// Grouped version of STREETS — used by SmartInput groupedOptions prop
const STREET_GROUPS = [
  { group:"National Highways", icon:"🛣️", items:[
    "Hosur Road (NH 44)","Outer Ring Road (NH 275)","NH 75",
  ]},
  { group:"Major Roads", icon:"🚗", items:[
    "Neeladri Road","Veerasandra Road",
    "Gollahalli Main Road","Shikaripalya Main Road","Kammasandra Main Road",
    "Doddathogur Main Road","Doddanagamangala Road","Huskur Road",
    "Shanthi Pura Main Road","ITC 5 Path (Doddanagamangala)",
    "Veerasandra Main Road, EC Phase 2","BTM Phase 1 Road",
    "Anantha Nagar Road, Kammasandra","GPR Royale Layout Road",
    "Konappana Agrahara Main Road","Hebbagodi Main Road","Bommasandra Ring Road",
    "Velankani Drive","Neotown Main Road","Smondoville Road",
    "Electronic City Elevated Expressway","Electronic City Service Road",
    "Jigani Road","Chandapura–Anekal Road","NICE Road","Sarjapur Road",
    "Gollahalli–Electronic City Road",
  ]},
  { group:"Campus & Tech Park Avenues", icon:"💼", items:[
    "Infosys Avenue","Hewlett Packard Avenue",
    "Bangalore Bioinnovation Centre Road","Symbiosis–CGI Road",
    "Abbaiah Reddy Street","Lotus Path",
    "Infosys Gate Road","Wipro Gate Road (Gate 13)",
  ]},
  { group:"EC Phase 1 Cross Roads", icon:"🔢", items:[
    "1st Cross, EC Phase 1","2nd Cross, EC Phase 1","3rd Cross, EC Phase 1",
    "4th Cross Road, EC Phase 1","5th Cross Road, EC Phase 1",
    "6th Cross Road, EC Phase 1","11th Cross Road, EC Phase 1",
    "12th Cross Road, EC Phase 1","13th Cross Road, EC Phase 1",
    "16th Cross Road, EC Phase 1",
  ]},
  { group:"EC Phase 2 Main Roads", icon:"🔢", items:[
    "1st Main Road, EC Phase 2","2nd Main Road, EC Phase 2",
    "4th Main Road, EC Phase 2","9th Cross Road, EC Phase 2",
  ]},
  { group:"Local Streets", icon:"🏘️", items:[
    "Bachappa Road","Veerasandra Main Road",
  ]},
];
const LANDMARKS = [
  // IT Campuses
  "Infosys Campus (EC Phase 1)","Wipro Campus (Phase 1, Gate 13)",
  "Tech Mahindra (EC Phase 2)","Biocon","BEML Complex",
  "DXC Technologies","Velankani Tech Park",
  // Malls & Commercial
  "EC Mall","Forum Mall (Hosur Rd)","M5 Ecity Mall","Neotown",
  // Banks & ATMs
  "HDFC Bank, EC Phase 2","State Bank of India, Electronic City",
  "Canara Bank, Electronic City","ICICI Bank, Electronic City",
  // Transport
  "Electronic City Metro Station","Hebbagodi Bus Terminal",
  "BMTC Depot, Electronic City",
  "Heelalige Railway Station","Karmelaram Railway Station",
  // Hotels
  "Golden Tulip Hotel, EC Phase 1","Lemon Tree Hotel, Electronic City",
  // Educational Institutes
  "IIIT Bangalore","Welingkar Institute of Management",
  "ISBR Business School","Symbiosis Institute, Electronic City",
  "Sri Chaitanya School, EC Phase 1",
  "Gitam University Bangalore (EC Phase 1)",
  "IZee Business School (Konappana Agrahara)",
  "Suvidya Institute (Electronics City)",
  // Healthcare
  "Trinity Healthcare Clinic","NIMHANS (Hosur Road)",
  // Police & Civic
  "Electronics City Traffic Police Station",
  "Electronic City Fire Station",
  // Places of Worship
  "Shirdi Sai Baba Temple, Gollahalli",
  "Sri Ganesha Temple, Gollahalli",
  "Kaveramma Temple, EC Phase 1",
  "Masjide Abbas, Shikaripalya",
  "Madeena Masjid, Shikaripalya",
  "Noor Masjid, Shikaripalya",
  // Parks & Recreation
  "Electronics City Park","Neeladri Nagar Park",
  "Doddathogur Lake Park","Veerasandra Lake","Heelalige Lake",
  "Huskur Lake","Bommasandra Park","Begur Fort & Lake",
];

// ─── Parks & Recreation (EC area) ────────────────────────────────────────────────
const PARKS = [
  {
    name:"Electronics City Park", area:"EC Phase 1",        type:"Park",
    icon:"🌳", desc:"Main community park near Infosys campus. Popular for morning walks and evening strolls.",
    timings:"5:00 AM – 8:00 PM",  mapX:38, mapY:38,
  },
  {
    name:"Neeladri Nagar Park",   area:"Neeladri Nagar",    type:"Park",
    icon:"🌿", desc:"Neighbourhood park with jogging track and children's play area.",
    timings:"5:30 AM – 8:00 PM",  mapX:52, mapY:68,
  },
  {
    name:"Doddathogur Lake",      area:"Doddathogur",       type:"Lake",
    icon:"🏞", desc:"Scenic lake with walking trail. Good spot for birdwatching in the early mornings.",
    timings:"Open all day",       mapX:44, mapY:50,
  },
  {
    name:"Veerasandra Lake",      area:"Veerasandra",       type:"Lake",
    icon:"🏞", desc:"Peaceful lake with walking path. Often used for morning fitness walks.",
    timings:"Open all day",       mapX:58, mapY:56,
  },
  {
    name:"Heelalige Lake",        area:"Heelalige",         type:"Lake",
    icon:"🏞", desc:"Lake near Heelalige railway station. Quiet retreat from the IT bustle.",
    timings:"Open all day",       mapX:28, mapY:44,
  },
  {
    name:"Huskur Lake",           area:"Huskur Road",       type:"Lake",
    icon:"🦅", desc:"Bird-watching hotspot. Migratory birds visit in winter months (Oct–Feb).",
    timings:"Open all day",       mapX:64, mapY:67,
  },
  {
    name:"Bommasandra Park",      area:"Bommasandra",       type:"Park",
    icon:"🌳", desc:"Community park near the industrial area. Maintained by BBMP.",
    timings:"6:00 AM – 7:30 PM",  mapX:72, mapY:60,
  },
  {
    name:"Begur Fort & Lake",     area:"Begur (~3 km)",     type:"Heritage + Lake",
    icon:"🏰", desc:"Historic fort with a lake. Popular weekend outing for EC families. Features ancient temple.",
    timings:"Open all day",       mapX:34, mapY:62,
  },
  {
    name:"Silk Board–EC Cycling Track", area:"Hosur Road",  type:"Cycling / Jogging",
    icon:"🚴", desc:"Dedicated cycling and jogging stretch along Hosur Road. Best before 7 AM on weekdays.",
    timings:"Best: 5:00–7:30 AM", mapX:48, mapY:24,
  },
];

// ─── Supermarkets & Grocery (EC area) ────────────────────────────────────────────
const SUPERMARKETS = [
  {
    name:"Reliance Fresh",         area:"EC Phase 1",
    icon:"🛒", type:"Supermarket",
    desc:"Daily essentials, fresh produce, dairy. Near Infosys Gate.",
    timings:"8:00 AM – 10:00 PM",  mapX:40, mapY:34,
  },
  {
    name:"More Supermarket",       area:"EC Phase 1",
    icon:"🛒", type:"Supermarket",
    desc:"Full supermarket — staples, produce, household items.",
    timings:"8:00 AM – 10:00 PM",  mapX:46, mapY:28,
  },
  {
    name:"Nilgiri's",              area:"EC Phase 2",
    icon:"🥛", type:"Supermarket",
    desc:"Fresh dairy, bakery, packaged foods and beverages.",
    timings:"8:00 AM – 9:30 PM",   mapX:62, mapY:44,
  },
  {
    name:"Spencer's",              area:"EC Phase 2",
    icon:"🛍", type:"Supermarket",
    desc:"Mid-size supermarket with apparel, electronics and groceries.",
    timings:"9:00 AM – 10:00 PM",  mapX:66, mapY:50,
  },
  {
    name:"Safal / Mother Dairy",   area:"EC Phase 1",
    icon:"🥦", type:"Fresh Produce",
    desc:"Fresh fruits, vegetables and dairy at subsidised prices.",
    timings:"7:00 AM – 8:00 PM",   mapX:36, mapY:32,
  },
  {
    name:"D-Mart",                 area:"Hosur Main Road, EC",
    icon:"🏬", type:"Hypermarket",
    desc:"D-Mart at Survey No.21, Hosur Main Road, Electronic City. Bulk buying hub for EC residents.",
    timings:"8:00 AM – 10:00 PM",  mapX:71, mapY:63,
  },
  {
    name:"Spar Hypermarket",       area:"Silk Board (~4 km)",
    icon:"🏬", type:"Hypermarket",
    desc:"Full-format hypermarket on Hosur Road. Wide international brands selection.",
    timings:"9:00 AM – 10:00 PM",  mapX:50, mapY:14,
  },
  {
    name:"Local Kirana – Neeladri Nagar", area:"Neeladri Nagar",
    icon:"🏪", type:"Kirana / Daily Needs",
    desc:"Neighbourhood kirana for daily top-ups — milk, eggs, snacks, basics.",
    timings:"7:00 AM – 9:00 PM",   mapX:53, mapY:70,
  },
  {
    name:"Local Kirana – Doddathogur",   area:"Doddathogur",
    icon:"🏪", type:"Kirana / Daily Needs",
    desc:"Local grocery store for residents of Doddathogur and surrounding layouts.",
    timings:"7:00 AM – 9:00 PM",   mapX:43, mapY:52,
  },
  {
    name:"Local Kirana – Gollahalli",    area:"Gollahalli",
    icon:"🏪", type:"Kirana / Daily Needs",
    desc:"Neighbourhood store serving Gollahalli and Shikaripalya residents.",
    timings:"7:00 AM – 9:00 PM",   mapX:30, mapY:38,
  },
];

// ─── Schools & Daycare (EC area) ─────────────────────────────────────────────────
const SCHOOLS = [
  // K–12 Schools
  {
    name:"Delhi Public School (DPS)",     area:"EC Phase 1",        icon:"🏫",
    type:"CBSE · K–12",
    desc:"One of EC's most sought-after schools. Strong academics, sports and extracurriculars.",
    timings:"8:00 AM – 3:30 PM", phone:"080 2783 2020", mapX:40, mapY:26,
  },
  {
    name:"National Public School (NPS)",  area:"EC Phase 1",        icon:"🏫",
    type:"CBSE · K–12",
    desc:"Well-regarded school known for board exam results and co-curricular activities.",
    timings:"8:00 AM – 3:00 PM", phone:"080 2852 4455", mapX:44, mapY:22,
  },
  {
    name:"Harvest International School",  area:"EC Phase 1",        icon:"🏫",
    type:"CBSE + Cambridge · K–12",
    desc:"Dual-curriculum school offering CBSE and Cambridge pathways from KG to Grade 12.",
    timings:"8:00 AM – 3:30 PM", phone:"080 4168 3000", mapX:38, mapY:30,
  },
  {
    name:"Orchids The International School", area:"EC Phase 2",     icon:"🏫",
    type:"CBSE · K–12",
    desc:"Modern campus with activity-based learning. Strong focus on holistic development.",
    timings:"8:00 AM – 3:30 PM", phone:"1800 102 3737", mapX:62, mapY:42,
  },
  {
    name:"Sri Chaitanya School",          area:"EC Phase 1",        icon:"🏫",
    type:"CBSE · K–12",
    desc:"Popular for IIT/NEET foundation from Class 6. Competitive academic environment.",
    timings:"7:30 AM – 3:30 PM", phone:"080 2783 0000", mapX:36, mapY:36,
  },
  {
    name:"DAV Public School",             area:"EC Phase 2",        icon:"🏫",
    type:"CBSE · K–12",
    desc:"DAV group school with values-based education. Hindi medium option available.",
    timings:"8:00 AM – 3:00 PM", phone:"080 4121 9900", mapX:64, mapY:48,
  },
  {
    name:"Ryan International School",    area:"Bommasandra",        icon:"🏫",
    type:"CBSE · K–12",
    desc:"Large campus near Bommasandra. Good sports facilities and tech labs.",
    timings:"8:00 AM – 3:30 PM", phone:"080 2783 5555", mapX:70, mapY:58,
  },
  {
    name:"Ebenezer International School", area:"Neeladri Nagar",    icon:"🏫",
    type:"CBSE · K–12",
    desc:"Community-oriented school in Neeladri Nagar. Affordable fees, good faculty.",
    timings:"8:00 AM – 3:00 PM", phone:"080 2783 1234", mapX:54, mapY:66,
  },
  {
    name:"Kendriya Vidyalaya",            area:"Electronic City",   icon:"🏛",
    type:"CBSE · K–12 (Govt)",
    desc:"Central government school. Priority for govt employees. Subsidised fees.",
    timings:"7:30 AM – 2:30 PM", phone:"080 2852 0101", mapX:48, mapY:32,
  },
  {
    name:"Podar International School",   area:"EC Phase 2",         icon:"🏫",
    type:"CBSE · K–12",
    desc:"Modern infrastructure with strong focus on digital learning.",
    timings:"8:00 AM – 3:30 PM", phone:"022 6633 5555", mapX:66, mapY:44,
  },
  // Preschools & Daycares
  {
    name:"EuroKids Preschool",           area:"EC Phase 1",         icon:"👶",
    type:"Preschool · Age 1.5–6",
    desc:"Play-based curriculum. Extended daycare available till 7 PM.",
    timings:"8:30 AM – 7:00 PM", phone:"1800 210 8008", mapX:42, mapY:24,
  },
  {
    name:"Kidzee",                       area:"EC Phase 2",         icon:"👶",
    type:"Preschool · Age 1.5–6",
    desc:"Structured EYFS curriculum. AC classrooms with trained Montessori staff.",
    timings:"8:30 AM – 6:30 PM", phone:"1800 200 4444", mapX:60, mapY:40,
  },
  {
    name:"Bachpan Play School",          area:"Neeladri Nagar",     icon:"👶",
    type:"Preschool + Daycare",
    desc:"Neighbourhood preschool with affordable fees. Good staff-to-child ratio.",
    timings:"8:00 AM – 6:00 PM", phone:"080 4500 5000", mapX:56, mapY:64,
  },
  {
    name:"Maharishi Global School",    area:"EC Phase 1 (near BHEL)",   icon:"🏫",
    type:"CBSE · K–12",
    desc:"NDR Campus near BHEL Signal, Electronic City. Good academics and infrastructure.",
    timings:"8:00 AM – 3:30 PM", phone:"080 2852 9000", mapX:50, mapY:28,
  },
  {
    name:"SFS Academy",                area:"Kammasandra, EC Phase 1",  icon:"🏫",
    type:"CBSE · K–12",
    desc:"SFS Academy at Kammasandra, Electronic City. Serves Ananth Nagar and nearby layouts.",
    timings:"8:00 AM – 3:00 PM", phone:"080 4500 1234", mapX:56, mapY:46,
  },
  {
    name:"Shree Ananthnagar Vidyaniketan", area:"Ananth Nagar, EC Phase 1", icon:"🏫",
    type:"State Board · K–10",
    desc:"Local Kannada-medium school at 25th Cross, Shree Ananth Nagar. Affordable fees.",
    timings:"8:00 AM – 2:30 PM", phone:"080 4500 5678", mapX:54, mapY:44,
  },
  {
    name:"Pavithra Public High School", area:"Hebbagodi",               icon:"🏫",
    type:"State Board · K–10",
    desc:"School near Hebbagodi Arch, Electronic City. Serves Hebbagodi and Bommasandra layouts.",
    timings:"8:00 AM – 2:30 PM", phone:"080 2783 6789", mapX:26, mapY:55,
  },
];

// ─── Hospitals & Clinics (EC area) ───────────────────────────────────────────────
const HOSPITALS = [
  {
    name:"Narayana Health City",       area:"Bommasandra",           icon:"🏥",
    type:"Multi-Speciality",
    desc:"One of India's largest hospitals. Full emergency, ICU, cardiac, cancer care. 24×7.",
    timings:"24 Hours",  phone:"1800 102 6672", mapX:72, mapY:65,
  },
  {
    name:"Fortis Hospital",            area:"Hosur Road (~5 km)",    icon:"🏥",
    type:"Multi-Speciality",
    desc:"Fortis group hospital with advanced surgery, orthopaedics and neurology.",
    timings:"24 Hours",  phone:"080 6621 4444", mapX:46, mapY:16,
  },
  {
    name:"Trinity Healthcare Clinic",  area:"EC Phase 1",            icon:"🏥",
    type:"Clinic / OPD",
    desc:"General physician, paediatrics, gynaecology OPD. Nearest clinic for EC Phase 1.",
    timings:"9:00 AM – 9:00 PM", phone:"080 4968 0000", mapX:40, mapY:28,
  },
  {
    name:"Manipal Hospital",           area:"Sarjapur (~8 km)",      icon:"🏥",
    type:"Multi-Speciality",
    desc:"Manipal group tertiary hospital. Strong ortho, neuro and transplant units.",
    timings:"24 Hours",  phone:"080 2502 4444", mapX:78, mapY:28,
  },
  {
    name:"Sparsh Hospital",            area:"EC Phase 2",            icon:"🏥",
    type:"Orthopaedics Speciality",
    desc:"India's leading orthopaedic chain. Sports injuries, joint replacement, spine.",
    timings:"24 Hours",  phone:"080 4600 0000", mapX:62, mapY:46,
  },
  {
    name:"PHC Doddathogur",            area:"Doddathogur",           icon:"🏥",
    type:"Govt Primary Health Centre",
    desc:"Government PHC serving Doddathogur, Kammasandra and nearby villages. Free OPD.",
    timings:"9:00 AM – 5:00 PM", phone:"080 2852 0200", mapX:44, mapY:52,
  },
  {
    name:"NIMHANS",                    area:"Hosur Road (~6 km)",    icon:"🏥",
    type:"Mental Health (Govt)",
    desc:"National Institute of Mental Health and Neurosciences. OPD by appointment.",
    timings:"9:00 AM – 4:00 PM", phone:"080 4611 5900", mapX:40, mapY:12,
  },
];

// ─── Petrol Pumps (EC area) ───────────────────────────────────────────────────────
const PETROL_PUMPS = [
  {
    name:"HPCL Petrol Pump",           area:"Neeladri Road, EC Ph1", icon:"⛽",
    type:"HPCL",
    desc:"24-hour fuel station on Neeladri Road. Petrol, diesel, air & CNG.",
    timings:"24 Hours",  mapX:50, mapY:36,
  },
  {
    name:"BPCL Petrol Pump",           area:"EC Phase 2",            icon:"⛽",
    type:"BPCL",
    desc:"Bharat Petroleum outlet near EC Phase 2. Petrol, diesel, lubricants.",
    timings:"24 Hours",  mapX:62, mapY:50,
  },
  {
    name:"Indian Oil Petrol Pump",     area:"Hosur Road (near EC)",  icon:"⛽",
    type:"Indian Oil",
    desc:"Indian Oil station on Hosur Road service road. Petrol, diesel, EV charging bay.",
    timings:"24 Hours",  mapX:44, mapY:16,
  },
  {
    name:"HP Petrol Pump",             area:"Bommasandra",           icon:"⛽",
    type:"HP",
    desc:"HP pump near Bommasandra Junction. Petrol, diesel, tyre-air.",
    timings:"6:00 AM – 10:00 PM", mapX:68, mapY:60,
  },
  {
    name:"Shell Petrol Pump",          area:"Hosur Road",            icon:"⛽",
    type:"Shell",
    desc:"Shell premium fuel station. Petrol, diesel, Shell V-Power and convenience store.",
    timings:"24 Hours",  mapX:38, mapY:14,
  },
];

// ─── Hotels & Stay (EC area) ──────────────────────────────────────────────────────
const HOTELS = [
  {
    name:"Golden Tulip Hotel",         area:"EC Phase 1",            icon:"🏨",
    type:"4-Star",
    desc:"Business hotel with banquet halls, restaurant and pool. Popular for corporate stays.",
    timings:"24 Hours",  phone:"080 4040 4040", mapX:38, mapY:34,
  },
  {
    name:"Lemon Tree Hotel",           area:"Electronic City",       icon:"🏨",
    type:"3-Star",
    desc:"Comfortable mid-scale hotel near IT campuses. Restaurant, bar and gym.",
    timings:"24 Hours",  phone:"080 6175 6175", mapX:44, mapY:38,
  },
  {
    name:"Treebo Trend",               area:"EC Phase 2",            icon:"🏨",
    type:"Budget",
    desc:"Clean, affordable Treebo-certified hotel. Good for short corporate or family stays.",
    timings:"24 Hours",  phone:"1800 266 0000", mapX:64, mapY:52,
  },
  {
    name:"FabHotel EC Phase 1",        area:"EC Phase 1",            icon:"🏨",
    type:"Budget",
    desc:"Budget hotel with AC rooms and complimentary breakfast. Well-reviewed.",
    timings:"24 Hours",  phone:"1800 212 4545", mapX:46, mapY:32,
  },
  {
    name:"OYO Rooms EC Phase 2",       area:"EC Phase 2",            icon:"🏨",
    type:"Budget",
    desc:"Multiple OYO-certified guesthouses in EC Phase 2. Book via OYO app.",
    timings:"24 Hours",  phone:"093 1393 1393", mapX:66, mapY:46,
  },
  {
    name:"Shivam Hotel",               area:"EC Phase 2",               icon:"🏨",
    type:"Budget",
    desc:"Budget hotel beside Tech Mahindra back gate, opp. TCS. Popular with IT professionals.",
    timings:"24 Hours",  phone:"080 4500 2222", mapX:60, mapY:48,
  },
  {
    name:"Ecity Luxury Stay",          area:"Shanthipura, EC Phase 2",  icon:"🏨",
    type:"PG / Serviced Apt",
    desc:"GPR Huskur area. Serviced apartments near APMC Wholesale Fruit Market.",
    timings:"24 Hours",  mapX:58, mapY:42,
  },
  {
    name:"Royal Delux PG",             area:"Huskur Gate",              icon:"🏨",
    type:"PG / Guest House",
    desc:"PG accommodation at 5th Cross, GPR Royale Layout, Huskur Gate. Good for long stays.",
    timings:"24 Hours",  mapX:64, mapY:40,
  },
];

// ─── Temples & Places of Worship (EC area) ────────────────────────────────────────
const TEMPLES = [
  {
    name:"Kaveramma Temple",           area:"EC Phase 1",            icon:"🛕",
    type:"Hindu Temple",
    desc:"Presiding deity of Electronic City. Annual Kaveramma Jatre festival draws large crowds.",
    timings:"6:00 AM – 8:00 PM", mapX:42, mapY:32,
  },
  {
    name:"Shirdi Sai Baba Temple",     area:"Gollahalli",            icon:"🛕",
    type:"Hindu Temple",
    desc:"Popular Sai Baba temple in Gollahalli. Bhajans on Thursdays.",
    timings:"6:00 AM – 8:30 PM", mapX:30, mapY:36,
  },
  {
    name:"Sri Ganesha Temple",         area:"Gollahalli",            icon:"🛕",
    type:"Hindu Temple",
    desc:"Neighbourhood Ganesha temple. Vinayaka Chaturthi celebrations are grand.",
    timings:"6:00 AM – 8:00 PM", mapX:28, mapY:40,
  },
  {
    name:"Anjaneya Temple",            area:"Veerasandra",           icon:"🛕",
    type:"Hindu Temple",
    desc:"Hanuman temple in Veerasandra. Saturdays are especially busy.",
    timings:"6:00 AM – 8:30 PM", mapX:56, mapY:58,
  },
  {
    name:"Doddathogur Anjaneya Temple",area:"Doddathogur",           icon:"🛕",
    type:"Hindu Temple",
    desc:"Ancient Anjaneya temple in Doddathogur village. Peaceful surroundings.",
    timings:"6:00 AM – 7:30 PM", mapX:44, mapY:48,
  },
  {
    name:"Murugan Temple",             area:"EC Phase 2",            icon:"🛕",
    type:"Hindu Temple",
    desc:"Murugan temple serving the large Tamil community in EC Phase 2.",
    timings:"6:00 AM – 8:00 PM", mapX:60, mapY:50,
  },
  {
    name:"Masjide Abbas",              area:"Shikaripalya",          icon:"🕌",
    type:"Mosque",
    desc:"Main mosque serving the Shikaripalya community. Friday Jumu'ah prayers.",
    timings:"5:00 AM – 9:00 PM", mapX:32, mapY:42,
  },
  {
    name:"Madeena Masjid",             area:"Shikaripalya",          icon:"🕌",
    type:"Mosque",
    desc:"Neighbourhood mosque in Shikaripalya. Five daily prayers.",
    timings:"5:00 AM – 9:00 PM", mapX:26, mapY:44,
  },
  {
    name:"St. Mary's Church",          area:"EC Phase 1",            icon:"⛪",
    type:"Church",
    desc:"Catholic church serving EC's Christian community. Sunday Mass at 7 AM and 9 AM.",
    timings:"Sun Mass 7 AM & 9 AM", mapX:44, mapY:26,
  },
  {
    name:"Muneshwara Temple",          area:"EC Phase 2",               icon:"🛕",
    type:"Hindu Temple",
    desc:"Muneshwara Temple in Electronic City Phase II. Local deity temple, peaceful surroundings.",
    timings:"6:00 AM – 8:00 PM", mapX:56, mapY:44,
  },
  {
    name:"Sri Kaveramma Temple",       area:"Veerasandra, EC Phase 2",  icon:"🛕",
    type:"Hindu Temple",
    desc:"Sri Kaveramma Temple on Veerasandra Main Road. Popular among IT professionals.",
    timings:"6:00 AM – 8:30 PM", mapX:58, mapY:54,
  },
  {
    name:"Fruit Market Masjid",        area:"Gulimangala",              icon:"🕌",
    type:"Mosque",
    desc:"Masjid near the fruit market in Gulimangala, EC Phase 2 area.",
    timings:"5:00 AM – 9:00 PM", mapX:62, mapY:56,
  },
  {
    name:"Masjid Maimun-O-Shams",      area:"Konappana Agrahara",       icon:"🕌",
    type:"Mosque",
    desc:"Masjid on Service Road, Muniswamy Layout, Konappana Agrahara.",
    timings:"5:00 AM – 9:00 PM", mapX:54, mapY:38,
  },
  {
    name:"Masjid Abu Ubaida",          area:"Gollahalli",               icon:"🕌",
    type:"Mosque",
    desc:"Masjid in Gollahalli serving the local Muslim community.",
    timings:"5:00 AM – 9:00 PM", mapX:26, mapY:42,
  },
];

// ─── Cinemas & Entertainment (near EC) ───────────────────────────────────────────
const CINEMAS = [
  {
    name:"Srinivasa Chitramandira",    area:"Hebbagodi (~2 km)",        icon:"🎬",
    type:"Single Screen",
    desc:"Local theatre on Bhavani Road, Hebbagodi. Kannada and Tamil films. Budget-friendly.",
    timings:"10:00 AM – 10:00 PM", mapX:28, mapY:58,
  },
  {
    name:"Shrinivasa Theatre",         area:"EC Phase 2 (Bhavani Rd)",  icon:"🎬",
    type:"Single Screen",
    desc:"Popular local theatre in Electronic City. Shows Kannada, Telugu and Tamil films.",
    timings:"10:00 AM – 10:30 PM", mapX:32, mapY:56,
  },
  {
    name:"Sri Venkateshwara Theatre",  area:"Konappana Agrahara",       icon:"🎬",
    type:"Single Screen",
    desc:"Neighbourhood theatre on Hosur Road, Konappana Agrahara. Kannada, Tamil films.",
    timings:"10:00 AM – 10:00 PM", mapX:56, mapY:36,
  },
  {
    name:"Sre Venkata Theater",        area:"Konappana Agrahara",       icon:"🎬",
    type:"Single Screen",
    desc:"Local single-screen theatre on Service Road, Konappana Agrahara.",
    timings:"10:00 AM – 10:00 PM", mapX:58, mapY:38,
  },
  {
    name:"PVR Cinemas – Forum Mall",   area:"Hosur Road (~4 km)",       icon:"🎬",
    type:"Multiplex",
    desc:"Nearest PVR multiplex. Latest releases in Hindi, Tamil, Kannada, Telugu, English.",
    timings:"10:00 AM – 11:30 PM", phone:"0844 2144 444", mapX:44, mapY:12,
  },
];

// ─── ATMs (EC area) ───────────────────────────────────────────────────────────────
const ATMS = [
  {
    name:"SBI ATM",                    area:"EC Phase 1",            icon:"🏧",
    type:"State Bank of India",
    desc:"SBI branch ATM on EC Phase 1 main road. 24-hour access.",
    timings:"24 Hours", mapX:40, mapY:30,
  },
  {
    name:"HDFC Bank ATM",              area:"EC Phase 2",            icon:"🏧",
    type:"HDFC Bank",
    desc:"HDFC ATM near EC Phase 2 main junction.",
    timings:"24 Hours", mapX:62, mapY:44,
  },
  {
    name:"ICICI Bank ATM",             area:"EC Phase 1",            icon:"🏧",
    type:"ICICI Bank",
    desc:"ICICI ATM inside IT campus service road. Accessible to all.",
    timings:"24 Hours", mapX:44, mapY:26,
  },
  {
    name:"Canara Bank ATM",            area:"EC Phase 1",            icon:"🏧",
    type:"Canara Bank",
    desc:"Canara Bank ATM near Electronic City main bus stop.",
    timings:"24 Hours", mapX:38, mapY:28,
  },
  {
    name:"Axis Bank ATM",              area:"Neeladri Nagar",        icon:"🏧",
    type:"Axis Bank",
    desc:"Axis Bank ATM in Neeladri Nagar. Convenient for apartment residents.",
    timings:"24 Hours", mapX:52, mapY:72,
  },
  {
    name:"Kotak Bank ATM",             area:"EC Phase 2",            icon:"🏧",
    type:"Kotak Mahindra Bank",
    desc:"Kotak ATM near EC Phase 2 commercial area.",
    timings:"24 Hours", mapX:64, mapY:46,
  },
  {
    name:"Yes Bank ATM",               area:"Hosur Road",            icon:"🏧",
    type:"Yes Bank",
    desc:"Yes Bank ATM on Hosur Road service road near EC entrance.",
    timings:"24 Hours", mapX:42, mapY:14,
  },
  {
    name:"Doddathogur SBI ATM",        area:"Doddathogur",           icon:"🏧",
    type:"State Bank of India",
    desc:"SBI ATM serving Doddathogur, Kammasandra and Neotown residents.",
    timings:"24 Hours", mapX:46, mapY:54,
  },
  {
    name:"Karnataka Bank ATM",         area:"Kammasandra, EC Phase 2",  icon:"🏧",
    type:"Karnataka Bank",
    desc:"Karnataka Bank ATM on Anantha Nagar Road, Kammasandra.",
    timings:"24 Hours", mapX:58, mapY:50,
  },
  {
    name:"Central Bank of India ATM",  area:"Kammasandra, EC Phase 2",  icon:"🏧",
    type:"Central Bank of India",
    desc:"Central Bank ATM serving Kammasandra and Ananth Nagar residents.",
    timings:"24 Hours", mapX:60, mapY:52,
  },
];

// ─── Restaurants & Cafés (EC area) ───────────────────────────────────────────────
const RESTAURANTS = [
  {
    name:"Hotel Millennium Plaza",     area:"Huskur Gate",              icon:"🍽️",
    type:"Multi-Cuisine",
    desc:"Popular restaurant at Huskur Gate opp. Vimalaya Hospital, near Biocon Factory.",
    timings:"7:00 AM – 11:00 PM", phone:"080 4500 3000", mapX:62, mapY:36,
  },
  {
    name:"Brunch & Munch",             area:"Huskur Gate",              icon:"🥗",
    type:"Café / Brunch",
    desc:"Café at Huskur Gate near Biocon. Brunch, sandwiches, healthy bowls.",
    timings:"8:00 AM – 10:00 PM", mapX:64, mapY:34,
  },
  {
    name:"Café Coffee Day",            area:"Hosur Main Road",          icon:"☕",
    type:"Café",
    desc:"CCD outlet next to Biocon on Hosur Main Road, Bommasandra. Coffee, snacks, free Wi-Fi.",
    timings:"7:00 AM – 10:30 PM", mapX:68, mapY:58,
  },
  {
    name:"Bhukkads",                   area:"Shanthipura, EC Phase 2",  icon:"🍽️",
    type:"Multi-Cuisine",
    desc:"Popular restaurant on Shanthipura Main Road, EC Phase 2. Budget meals and thalis.",
    timings:"11:00 AM – 11:00 PM", mapX:60, mapY:38,
  },
  {
    name:"Pizza Republic",             area:"EC Phase 2",               icon:"🍕",
    type:"Pizza / Fast Food",
    desc:"Pizza and fast food in Electronic City Phase II. Dine-in and delivery.",
    timings:"11:00 AM – 11:30 PM", mapX:62, mapY:40,
  },
  {
    name:"Veg Thali Corner",           area:"Neeladri Nagar",           icon:"🍛",
    type:"Vegetarian",
    desc:"Popular veg thali restaurant in Neeladri Nagar. Affordable and filling meals.",
    timings:"11:30 AM – 10:30 PM", mapX:52, mapY:68,
  },
  {
    name:"Darshini (EC Phase 1)",      area:"EC Phase 1",               icon:"☕",
    type:"South Indian / Darshini",
    desc:"Quick-service South Indian darshini near Infosys Gate. Idli, dosa, coffee.",
    timings:"6:30 AM – 10:00 PM", mapX:40, mapY:30,
  },
  {
    name:"Andhra Mess",                area:"Doddathogur",              icon:"🍽️",
    type:"Andhra / Non-Veg",
    desc:"Authentic Andhra meals and biryani in Doddathogur. Favourite of IT workers.",
    timings:"12:00 PM – 10:30 PM", mapX:44, mapY:50,
  },
];

// ─── Bus Stops (EC Phase 1 & surrounding) ────────────────────────────────────────
const BUS_STOPS = [
  // BMTC stops — EC Phase 1
  "Shikaripalya Cross","Electronic City Infosys Gate",
  "Electronic City Wipro Gate","Electronic City State Bank",
  "Dodda Togur","Electronic City Phase 1 (Main Stop)",
  "Gollahalli Bus Stop","Neotown Bus Stop",
  "Velankani Tech Park Stop","Neeladri Nagar Stop",
  // EC Phase 2 / surrounding
  "Electronic City Phase 2 Bus Stop","Hebbagodi Bus Terminal",
  "Bommasandra Bus Stop","Veerasandra Bus Stop",
  "Konappana Agrahara Bus Stop","Huskur Road Bus Stop",
  "Shanthipura Bus Stop","Huskur Gate Bus Stop",
  "Veerasandra (EC Phase 2) Bus Stop","BTM Phase 1 Bus Stop",
  "Electronic City Phase 2 (Main)","Gulimangala Bus Stop",
  // Railway stations (nearest)
  "Heelalige Railway Station","Karmelaram Railway Station",
];

// BMTC bus routes serving EC Phase 1
const BUS_ROUTES = [
  "G2 (Silk Board ↔ Electronic City)","V356Q","V375A","V505A","V505C",
  "335E (Majestic ↔ Electronic City)","KBS-14 (Kempegowda Bus Station)",
  "410D (Electronic City ↔ Bharathnagar)",
  "411D (Marathahalli Bridge ↔ Chandapura Circle)",
  "500H (Chandapura Circle ↔ K R Puram)",
  "500J (Chandapura Circle ↔ Yeshwanthpur)",
  "600 (Banashankari ↔ Banashankari)",
];

// ─── Helpline Numbers ────────────────────────────────────────────────────────────
const HELPLINES = [
  // National Emergency
  { cat:"Emergency",  icon:"🚨", name:"Police",                    phone:"100",           color:"#DC2626" },
  { cat:"Emergency",  icon:"🔥", name:"Fire Station",              phone:"101",           color:"#EA580C" },
  { cat:"Emergency",  icon:"🚑", name:"Ambulance",                 phone:"108",           color:"#DC2626" },
  { cat:"Emergency",  icon:"👩", name:"Women Helpline",            phone:"1091",          color:"#9333EA" },
  { cat:"Emergency",  icon:"👶", name:"Child Helpline",            phone:"1098",          color:"#2563EB" },
  { cat:"Emergency",  icon:"🚨", name:"Disaster Helpline",         phone:"1077",          color:"#B45309" },
  // Electronic City Local
  { cat:"EC Local",   icon:"👮", name:"EC Traffic Police Station", phone:"080 2852 3253", color:"#1D4ED8" },
  { cat:"EC Local",   icon:"👮", name:"Hebbagodi Police Station",  phone:"080 2783 5900", color:"#1D4ED8" },
  { cat:"EC Local",   icon:"🚒", name:"EC Fire Station",           phone:"080 2782 1101", color:"#EA580C" },
  { cat:"EC Local",   icon:"🏥", name:"Narayana Health (EC)",      phone:"1800 102 6672", color:"#059669" },
  { cat:"EC Local",   icon:"🏥", name:"Trinity Healthcare Clinic", phone:"080 4968 0000", color:"#059669" },
  // Utilities
  { cat:"Utilities",  icon:"⚡", name:"BESCOM (Power Outage)",     phone:"1912",          color:"#D97706" },
  { cat:"Utilities",  icon:"💧", name:"BWSSB (Water)",             phone:"1916",          color:"#0284C7" },
  { cat:"Utilities",  icon:"🔗", name:"BBMP Ward Office (EC)",     phone:"080 2252 0330", color:"#7C3AED" },
  { cat:"Utilities",  icon:"🏛", name:"Bangalore One (Citizens)",  phone:"080 2295 5568", color:"#6D28D9" },
  // Transport
  { cat:"Transport",  icon:"🚌", name:"BMTC Helpline (Toll-Free)", phone:"1800 425 1663", color:"#0369A1" },
  { cat:"Transport",  icon:"🚍", name:"KSRTC (Majestic)",          phone:"080 2226 9508", color:"#065F46" },
  { cat:"Transport",  icon:"🚇", name:"BMRCL Metro Helpline",      phone:"080 4969 4969", color:"#7C3AED" },
  // Medical
  { cat:"Medical",    icon:"🏥", name:"NIMHANS",                   phone:"080 4611 5900", color:"#059669" },
  { cat:"Medical",    icon:"💊", name:"Apollo Pharmacy (24hr)",    phone:"1860 500 1066", color:"#DC2626" },
  { cat:"Medical",    icon:"🩸", name:"Blood Bank (BBMP)",         phone:"104",           color:"#DC2626" },
  // Police / Citywide
  { cat:"Police",     icon:"🖥", name:"Cyber Crime Police",        phone:"080 2237 5522", color:"#1D4ED8" },
  { cat:"Police",     icon:"👮", name:"Commissioner of Police",    phone:"080 2294 2222", color:"#1E40AF" },
  { cat:"Police",     icon:"🚦", name:"Traffic Control Room",      phone:"080 2294 3131", color:"#1D4ED8" },
];

// ─── SmartInput ─────────────────────────────────────────────────────────────────
// groupedOptions: [{group, icon, items[]}]  – show category headers in dropdown
// options:        string[]                  – flat list (legacy / apartment picker)
// fromDropdown=true  → value came from a list pick   (trusted, no char-validation needed)
// fromDropdown=false → value was typed manually        (run stripFn + validate)
function SmartInput({ label, placeholder, options=[], groupedOptions=null, value, onChange, icon="🔍", filterFn, error }) {
  const [query,    setQuery]    = useState(value||"");
  const [open,     setOpen]     = useState(false);
  const [manual,   setManual]   = useState(false);
  const [confirmed,setConfirmed]= useState(!!value);
  const ref = useRef(null);

  useEffect(()=>{
    const h=e=>{ if(ref.current&&!ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown",h);
    return ()=>document.removeEventListener("mousedown",h);
  },[]);

  // Build a flat list from grouped options for easy filtering
  const allGroupedFlat = groupedOptions ? groupedOptions.flatMap(g=>g.items) : [];
  const effectiveOptions = groupedOptions ? allGroupedFlat : options;

  // When typing: flat filtered results; when browsing: use grouped layout (handled in render)
  const flatSuggestions = query.length>=1
    ? effectiveOptions.filter(o=>o.toLowerCase().includes(query.toLowerCase())).slice(0,10)
    : effectiveOptions.slice(0,6);

  const select=(opt)=>{ setQuery(opt); setConfirmed(true); setOpen(false); setManual(false); onChange(opt, true); };
  const goManual=()=>{
    const pre = filterFn ? filterFn(query) : query;
    setManual(true); setOpen(false); setConfirmed(false); setQuery(pre); onChange(pre, false);
  };
  const clear=()=>{ setQuery(""); setConfirmed(false); setManual(false); onChange("", false); setOpen(false); };
  const handleChange=(e)=>{ let v=e.target.value; if(filterFn) v=filterFn(v); setQuery(v); setConfirmed(false); onChange(v, false); if(!manual) setOpen(true); };

  // Renders a single option row with query highlight
  const OptionRow = ({opt, rowIcon}) => {
    const q = query.toLowerCase();
    const idx = q.length>0 ? opt.toLowerCase().indexOf(q) : -1;
    const b=idx>=0?opt.slice(0,idx):"", m=idx>=0?opt.slice(idx,idx+q.length):"", a=idx>=0?opt.slice(idx+q.length):opt;
    return (
      <button key={opt} onMouseDown={()=>select(opt)}
        className="w-full text-left px-4 py-2.5 flex items-center gap-2 transition-colors hover:bg-purple-50"
        style={{borderBottom:`1px solid ${C.border}`}}>
        <span className="text-sm flex-shrink-0" style={{color:C.muted}}>{rowIcon||"📍"}</span>
        <span className="text-sm font-medium" style={{color:C.text}}>
          {idx>=0?<>{b}<span className="font-black" style={{color:C.purple}}>{m}</span>{a}</>:opt}
        </span>
      </button>
    );
  };

  // Grouped browse view (no query typed): show section headers + items
  const GroupedList = () => (
    <>
      {groupedOptions.map(grp=>(
        <div key={grp.group}>
          <div className="px-4 py-1.5 flex items-center gap-1.5 sticky top-0"
            style={{background:"#F8F5FF",borderBottom:`1px solid ${C.border}`}}>
            <span className="text-sm">{grp.icon}</span>
            <span className="text-xs font-black tracking-wide uppercase" style={{color:C.purple}}>{grp.group}</span>
          </div>
          {grp.items.map(opt=><OptionRow key={opt} opt={opt} rowIcon={grp.icon}/>)}
        </div>
      ))}
    </>
  );

  // Flat filtered view (query typed): results from all groups
  const FlatList = () => (
    flatSuggestions.length>0?(
      flatSuggestions.map(opt=>{
        const grpIcon = groupedOptions
          ? (groupedOptions.find(g=>g.items.includes(opt))||{}).icon
          : "🏢";
        return <OptionRow key={opt} opt={opt} rowIcon={grpIcon||"🏢"}/>;
      })
    ):(
      <div className="px-4 py-4 text-center">
        <div className="text-2xl mb-1">🤔</div>
        <div className="text-sm font-bold" style={{color:C.text}}>No matches found</div>
        <div className="text-xs mt-0.5" style={{color:C.muted}}>Try different spelling or enter manually</div>
      </div>
    )
  );

  return (
    <div ref={ref} className="relative">
      {label && <label className="text-sm font-black mb-1.5 block" style={{color:C.text}}>{label}</label>}
      <div className="flex items-center rounded-xl px-3 py-2.5 gap-2"
        style={{background:"#fff",border:`2px solid ${error?C.coral:open?C.purple:confirmed?C.mint:C.border}`,transition:"border-color 0.15s"}}>
        <span className="text-base flex-shrink-0">{icon}</span>
        <input className="flex-1 text-sm font-medium bg-transparent focus:outline-none" style={{color:C.text}}
          placeholder={placeholder} value={query}
          onChange={handleChange} onFocus={()=>{ if(!manual) setOpen(true); }} autoComplete="off" />
        {confirmed&&!open&&(
          <span className="text-xs font-black px-2 py-0.5 rounded-full flex-shrink-0"
            style={{background:C.mintL,color:C.mint}}>✓</span>
        )}
        {query.length>0&&(
          <button onClick={clear} className="flex-shrink-0 text-sm font-black px-1" style={{color:C.muted}}>✕</button>
        )}
      </div>
      {manual&&(
        <div className="mt-1 flex items-center gap-1.5">
          <span className="text-xs" style={{color:C.muted}}>✏️ Entering manually –</span>
          <button onClick={()=>{setManual(false);setQuery("");onChange("",false);}} className="text-xs font-bold underline" style={{color:C.purple}}>
            Search instead
          </button>
        </div>
      )}
      {open&&!manual&&(
        <div className="absolute left-0 right-0 top-full mt-1.5 rounded-2xl overflow-auto z-50"
          style={{background:"#fff",border:`1.5px solid ${C.border}`,boxShadow:`0 8px 32px ${C.purple}18`,maxHeight:300}}>
          {/* Show grouped headers when browsing; flat filtered results when typing */}
          {groupedOptions && query.length===0 ? <GroupedList/> : <FlatList/>}
          <div className="px-4 py-2" style={{borderTop:`1.5px dashed ${C.border}`}}>
            <span className="text-xs font-semibold" style={{color:C.muted}}>Not in the list?</span>
          </div>
          <button onMouseDown={goManual} className="w-full text-left px-4 py-3 flex items-center gap-2"
            style={{background:C.purpleFg}}>
            <span className="text-sm">✏️</span>
            <div>
              <div className="text-sm font-black" style={{color:C.purple}}>
                Enter {query.length>0?`"${query}"` :"manually"}
              </div>
              <div className="text-xs" style={{color:C.muted}}>Type your own apartment / street name</div>
            </div>
          </button>
        </div>
      )}
    </div>
  );
}

// ─── Logo ───────────────────────────────────────────────────────────────────────
// MT mark: M = double-peak roofline · T = chimney/tower
// Four pillars: HOME · SECURITY (shield) · CONNECTING (WiFi arcs) · HELPFUL (♥ door)
function Logo({size=44}){
  return(
    <svg width={size} height={size} viewBox="0 0 52 52" fill="none">

      {/* ══ SECURITY — Shield body ══ */}
      <path d="M26 1 L49 10 L49 32 Q49 47 26 52 Q3 47 3 32 L3 10 Z"
        fill={C.purple}/>
      {/* Inner depth highlight */}
      <path d="M26 5 L45 13 L45 32 Q45 44 26 49 Q7 44 7 32 L7 13 Z"
        fill={C.purpleL} fillOpacity="0.16"/>

      {/* ══ CONNECTING — WiFi broadcast arcs above chimney ══ */}
      {/* Signal apex dot */}
      <circle cx="26" cy="3.5" r="1.5" fill={C.mint}/>
      {/* Outer arc — broadest reach */}
      <path d="M20 7.5 A6.5 6.5 0 0 0 32 7.5"
        stroke={C.mint} strokeWidth="2.2" strokeLinecap="round" fill="none"/>
      {/* Inner arc — closer signal */}
      <path d="M23 7.5 A3.1 3.1 0 0 0 29 7.5"
        stroke="white" strokeWidth="1.7" strokeLinecap="round" fill="none" opacity="0.8"/>

      {/* ══ T — chimney tower (T = Together / Transmit) ══ */}
      {/* T crossbar */}
      <rect x="18.5" y="8" width="15" height="3.5" rx="1.5" fill="white"/>
      {/* T vertical stem — drops to M valley */}
      <rect x="23.5" y="11.5" width="5" height="14.5" rx="1" fill="white"/>

      {/* ══ M — double-peak roofline (M = MyTown) ══ */}
      {/* Left peak (16,20)·valley (26,26)·right peak (36,20) spells M */}
      <path d="M6 30 L16 20 L26 26 L36 20 L46 30 Z" fill="white"/>

      {/* ══ HOME — house walls, windows ══ */}
      <rect x="8" y="29" width="36" height="16" rx="2" fill="white"/>
      {/* Left window */}
      <rect x="11" y="31" width="6" height="6" rx="1.2"
        fill={C.purple} fillOpacity="0.24"/>
      {/* Right window */}
      <rect x="35" y="31" width="6" height="6" rx="1.2"
        fill={C.purple} fillOpacity="0.24"/>
      {/* Mint door — welcoming entry */}
      <rect x="22" y="33.5" width="8" height="11.5" rx="1.5" fill={C.mint}/>

      {/* ══ HELPFUL — heart inside door ══ */}
      <circle cx="24.5" cy="37.5" r="2.2" fill="white" fillOpacity="0.92"/>
      <circle cx="27.5" cy="37.5" r="2.2" fill="white" fillOpacity="0.92"/>
      <path d="M22.5 38.5 L26 43 L29.5 38.5 Z" fill="white" fillOpacity="0.92"/>

    </svg>
  );
}

// ─── Avatar ─────────────────────────────────────────────────────────────────────
function Avatar({initials,color=C.purple,size=36}){
  return(
    <div className="flex items-center justify-center text-white font-black flex-shrink-0"
      style={{background:color,width:size,height:size,fontSize:size*0.37,borderRadius:size*0.3}}>
      {initials}
    </div>
  );
}

// ─── Verified ───────────────────────────────────────────────────────────────────
function Verified(){
  return(
    <span className="inline-flex items-center gap-1 text-xs font-bold px-2 py-0.5 rounded-full"
      style={{background:C.mintL,color:C.mint}}>
      <svg width="10" height="10" viewBox="0 0 10 10">
        <circle cx="5" cy="5" r="5" fill={C.mint}/>
        <path d="M3 5l1.5 1.5L7 3.5" stroke="white" strokeWidth="1.2" strokeLinecap="round"/>
      </svg>
      Verified
    </span>
  );
}

// ─── Bottom Nav ─────────────────────────────────────────────────────────────────
const TABS=[
  {id:"feed",      icon:"🏘",  label:"Feed",     grad:G.tabFeed},
  {id:"events",    icon:"📅",  label:"Events",   grad:G.tabEvents},
  {id:"community", icon:"🏛",  label:"Leaders",  grad:G.tabCommunity},
  {id:"messages",  icon:"✉️",  label:"Messages", grad:G.tabMessages},
  {id:"profile",   icon:"👤",  label:"Profile",  grad:G.tabProfile},
];
function BottomNav({tab,setTab}){
  const myPhase = ELECTION_PHASES[MY_STATS.area];
  const electionLive = myPhase==="voting" || myPhase==="pre_election";
  return(
    <nav style={{
        position:"fixed",bottom:0,left:0,right:0,
        maxWidth:480,margin:"0 auto",
        zIndex:50,
        background:"rgba(255,255,255,0.97)",
        backdropFilter:"blur(20px)",
        WebkitBackdropFilter:"blur(20px)",
        borderTop:`1px solid ${C.border}`,
        boxShadow:"0 -2px 16px rgba(92,45,145,0.08)",
        padding:"6px 8px calc(10px + env(safe-area-inset-bottom, 0px))",
      }}>
      <div style={{display:"flex",alignItems:"center",gap:4}}>
        {TABS.map((t,i)=>{
          const active=tab===t.id;
          // ── CENTER SLOT (index 2) transforms during active election ──
          if(i===2 && electionLive){
            const isVoting = myPhase==="voting";
            return(
              <button key={t.id} onClick={()=>setTab(t.id)}
                style={{
                  flex:1,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",
                  gap:2,paddingTop:7,paddingBottom:7,borderRadius:18,
                  background: isVoting
                    ? `linear-gradient(135deg,${C.crimsonM},${C.coral})`
                    : `linear-gradient(135deg,#E08A00,${C.marigold})`,
                  boxShadow:`0 4px 18px ${isVoting?C.coral:C.marigold}66`,
                  transform:"scale(1.05)",
                  position:"relative",border:"none",cursor:"pointer",
                }}>
                <span style={{
                  position:"absolute",inset:-3,borderRadius:21,
                  border:`2.5px solid ${isVoting?C.coral:C.marigold}`,
                  animation:"pulse 1.6s infinite",opacity:0.4,pointerEvents:"none",
                }}/>
                <span style={{fontSize:17,lineHeight:1,filter:"brightness(10)"}}>
                  {isVoting?"🗳":"📣"}
                </span>
                <span style={{fontSize:9,fontWeight:900,color:"#fff",lineHeight:1.2}}>
                  {isVoting?"VOTE NOW":"APPLY"}
                </span>
                <span style={{fontSize:8,color:"rgba(255,255,255,0.85)"}}>
                  {isVoting ? `${TERM_DATA.ep2.daysLeftVoting}d left` : "Election Open"}
                </span>
              </button>
            );
          }
          return(
            <button key={t.id} onClick={()=>setTab(t.id)}
              style={{
                flex:1,display:"flex",flexDirection:"column",alignItems:"center",gap:2,
                paddingTop:active?5:7,paddingBottom:active?5:5,
                borderRadius:14,cursor:"pointer",
                background:active?t.grad:"transparent",
                boxShadow:active?"0 3px 14px rgba(28,15,60,0.2)":"none",
                transition:"all 0.22s cubic-bezier(0.4,0,0.2,1)",
                border:"none",
              }}>
              <span style={{
                fontSize:active?19:16,lineHeight:1,
                transition:"all 0.22s",
                filter:active?"brightness(10)":"none",
              }}>{t.icon}</span>
              <span style={{
                fontSize:9,fontWeight:800,
                color:active?"#fff":C.muted,
                letterSpacing:active?"0.02em":"0",
                transition:"color 0.22s",
              }}>{t.label}</span>
            </button>
          );
        })}
      </div>
    </nav>
  );
}

const NOTIF_ITEMS=[
  {id:1, icon:"⚠️",  title:"Safety Alert",          body:"Suspicious activity near Gate 3, EC Phase 1",   time:"2 min ago",  col:"#FF6B7A", read:false},
  {id:2, icon:"🗳",  title:"Election Update",        body:"Nominations open for EC Phase 2 Community Admin",time:"1 hr ago",   col:"#D97706", read:false},
  {id:3, icon:"🎉",  title:"Event Reminder",         body:"Holi Celebration at Electronics City Park — tomorrow 6 PM",time:"3 hr ago",col:"#4F46E5",read:false},
  {id:4, icon:"✓",   title:"Account Verified",       body:"Your resident account has been approved",       time:"Yesterday",  col:"#00B89F", read:true},
  {id:5, icon:"📢",  title:"Community Announcement", body:"Water supply maintenance 9 AM–1 PM on 5th March", time:"Yesterday", col:"#5C2D91", read:true},
];

function TopBar({setScreen, onMenuOpen}){
  const [notifOpen, setNotifOpen] = useState(false);
  const [notifs, setNotifs] = useState(NOTIF_ITEMS);
  const unread = notifs.filter(n=>!n.read).length;
  const markAllRead = () => setNotifs(n=>n.map(x=>({...x,read:true})));
  const markRead = (id) => setNotifs(n=>n.map(x=>x.id===id?{...x,read:true}:x));

  return(
    <div style={{position:"fixed",top:0,left:0,right:0,zIndex:40,maxWidth:480,margin:"0 auto"}}>
    <header style={{
      padding:"10px 14px 10px",
      display:"flex",alignItems:"center",justifyContent:"space-between",
      background:"rgba(248,245,255,0.97)",
      backdropFilter:"blur(16px)",
      WebkitBackdropFilter:"blur(16px)",
      borderBottom:`1px solid ${C.border}`,
      boxShadow:"0 1px 0 rgba(92,45,145,0.08), 0 2px 12px rgba(92,45,145,0.06)",
    }}>
      <div style={{display:"flex",alignItems:"center",gap:10}}>
        {/* Hamburger */}
        <button onClick={onMenuOpen} aria-label="Open menu"
          style={{
            display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",
            gap:5,width:38,height:38,borderRadius:13,
            background:`linear-gradient(135deg,${C.purpleFg},#EAE0FF)`,
            border:`1px solid ${C.purple}22`,cursor:"pointer",
          }}>
          <span style={{display:"block",width:15,height:2,borderRadius:2,background:C.purple}}/>
          <span style={{display:"block",width:15,height:2,borderRadius:2,background:C.purple}}/>
          <span style={{display:"block",width:10,height:2,borderRadius:2,background:C.purpleL}}/>
        </button>
        {/* Logo + brand */}
        <div style={{display:"flex",alignItems:"center",gap:8}}>
          <div style={{
            width:36,height:36,borderRadius:11,
            background:"linear-gradient(135deg,#5C2D91,#7B4BB8)",
            display:"flex",alignItems:"center",justifyContent:"center",
            boxShadow:"0 3px 12px rgba(92,45,145,0.35)",
          }}>
            <Logo size={28}/>
          </div>
          <div>
            <div style={{fontWeight:900,fontSize:14,color:C.text,lineHeight:1.1}}>MyTown 360</div>
            <div style={{fontSize:11,fontWeight:700,color:C.mint,letterSpacing:"0.04em"}}>EC · Bangalore ✦</div>
          </div>
        </div>
      </div>
      <div style={{display:"flex",alignItems:"center",gap:8}}>
        {/* Bell button */}
        <button onClick={()=>setNotifOpen(o=>!o)} style={{
          position:"relative",padding:7,borderRadius:12,
          background:notifOpen?C.purple:C.purpleFg,
          border:`1px solid ${C.purple}22`,cursor:"pointer",
          boxShadow:notifOpen?"0 3px 12px rgba(92,45,145,0.35)":"none",
          transition:"all 0.18s",
        }}>
          <span style={{fontSize:17,filter:notifOpen?"brightness(10)":"none"}}>🔔</span>
          {unread>0&&(
            <span style={{
              position:"absolute",top:2,right:2,
              width:17,height:17,borderRadius:"50%",
              background:`linear-gradient(135deg,${C.crimsonM},${C.coral})`,
              color:"#fff",fontWeight:900,fontSize:9,
              display:"flex",alignItems:"center",justifyContent:"center",
              boxShadow:"0 2px 6px rgba(220,38,38,0.4)",
            }}>{unread}</span>
          )}
        </button>
        {/* Avatar */}
        <button onClick={()=>setScreen("profile")} style={{
          width:36,height:36,borderRadius:11,cursor:"pointer",
          background:"linear-gradient(135deg,#5C2D91,#8B5CF6)",
          color:"#fff",fontWeight:900,fontSize:12,
          border:"none",display:"flex",alignItems:"center",justifyContent:"center",
          boxShadow:"0 3px 12px rgba(92,45,145,0.4)",
          letterSpacing:"0.04em",
        }}>MT</button>
      </div>
    </header>

    {/* ── Notification panel (slides down) ── */}
    {notifOpen&&(
      <div style={{
        position:"absolute",top:"100%",right:0,left:0,zIndex:50,
        background:"#fff",
        borderBottom:`1px solid ${C.border}`,
        boxShadow:"0 12px 40px rgba(28,15,60,0.16)",
        animation:"fadeUp 0.2s ease",
      }}>
        {/* Panel header */}
        <div style={{padding:"12px 16px 10px",display:"flex",alignItems:"center",justifyContent:"space-between",borderBottom:`1px solid ${C.border}`}}>
          <div>
            <span style={{fontWeight:900,fontSize:14,color:C.text}}>Notifications</span>
            {unread>0&&<span style={{marginLeft:7,padding:"1px 8px",borderRadius:99,fontSize:10,fontWeight:800,background:`linear-gradient(135deg,${C.crimsonM},${C.coral})`,color:"#fff"}}>{unread} new</span>}
          </div>
          <div style={{display:"flex",gap:8,alignItems:"center"}}>
            {unread>0&&(
              <button onClick={markAllRead} style={{fontSize:11,fontWeight:700,color:C.mint,background:"none",border:"none",cursor:"pointer"}}>
                Mark all read
              </button>
            )}
            <button onClick={()=>setNotifOpen(false)} style={{
              width:28,height:28,borderRadius:8,background:C.purpleFg,
              border:"none",cursor:"pointer",color:C.purple,fontWeight:900,fontSize:14,
              display:"flex",alignItems:"center",justifyContent:"center",
            }}>✕</button>
          </div>
        </div>
        {/* Notification list */}
        <div style={{maxHeight:340,overflowY:"auto"}}>
          {notifs.map(n=>(
            <div key={n.id} onClick={()=>markRead(n.id)}
              style={{
                display:"flex",gap:11,padding:"11px 16px",
                background:n.read?"#fff":"linear-gradient(135deg,rgba(92,45,145,0.04),#fff)",
                borderBottom:`1px solid ${C.border}`,
                cursor:"pointer",
                borderLeft:`3px solid ${n.read?"transparent":n.col}`,
              }}>
              {/* Icon bubble */}
              <div style={{
                width:38,height:38,borderRadius:12,flexShrink:0,
                background:`linear-gradient(135deg,${n.col}22,${n.col}0A)`,
                border:`1.5px solid ${n.col}33`,
                display:"flex",alignItems:"center",justifyContent:"center",
                fontSize:17,
              }}>{n.icon}</div>
              {/* Text */}
              <div style={{flex:1,minWidth:0}}>
                <div style={{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:6}}>
                  <span style={{fontWeight:n.read?600:900,fontSize:12,color:C.text,lineHeight:1.3}}>{n.title}</span>
                  <span style={{fontSize:10,color:C.muted,flexShrink:0,marginTop:1}}>{n.time}</span>
                </div>
                <div style={{fontSize:11,color:C.muted,marginTop:2,lineHeight:1.4}}>{n.body}</div>
              </div>
              {/* Unread dot */}
              {!n.read&&<div style={{width:7,height:7,borderRadius:"50%",background:n.col,flexShrink:0,marginTop:5}}/>}
            </div>
          ))}
        </div>
        {/* Footer */}
        <div style={{padding:"10px 16px",textAlign:"center",borderTop:`1px solid ${C.border}`}}>
          <button onClick={()=>setNotifOpen(false)} style={{fontSize:12,fontWeight:700,color:C.purple,background:"none",border:"none",cursor:"pointer"}}>
            See all notifications →
          </button>
        </div>
      </div>
    )}
    </div>
  );
}

// ─── Sidebar Drawer ──────────────────────────────────────────────────────────
// Sidebar only contains items NOT already in the bottom nav
// Bottom nav covers: Feed · Events · Leaders · Messages · Profile
const SIDEBAR_ACTIONS=[
  { id:"map",            icon:"🗺",  label:"Neighbours Map",            sub:"Interactive map of your area",         color:C.purple  },
  { id:"community_apply",icon:"✍️",  label:"Apply for Community Admin",  sub:"Stand for election in your area",      color:C.mint, highlight:true },
  { id:"contact_admin",  icon:"📞",  label:"Contact Community Admin",    sub:"Message your area's current manager",  color:C.purple  },
];
const SIDEBAR_QUICK=[
  {icon:"🛡️", label:"Safety Alerts",    color:"#FF6B7A", id:"feed"},
  {icon:"🔧", label:"Service Providers", color:"#5C2D91", id:"feed"},
  {icon:"⭐", label:"Recommendations",   color:"#00B89F", id:"feed"},
  {icon:"🗺️", label:"Area Map",          color:"#4F46E5", id:"map"},
  {icon:"📞", label:"Helplines",         color:"#DC2626", id:"helplines"},
  {icon:"📅", label:"Events",            color:"#D97706", id:"events"},
];
function Sidebar({open, onClose, nav, activeTab}){
  useEffect(()=>{
    document.body.style.overflow = open ? "hidden" : "";
    return ()=>{ document.body.style.overflow=""; };
  },[open]);
  useEffect(()=>{
    const h=(e)=>{ if(e.key==="Escape") onClose(); };
    window.addEventListener("keydown",h);
    return ()=>window.removeEventListener("keydown",h);
  },[onClose]);
  return(
    <>
      {/* Backdrop */}
      <div onClick={onClose}
        style={{
          position:"fixed",inset:0,zIndex:40,
          background:"rgba(26,16,51,0.45)",
          backdropFilter:open?"blur(3px)":"none",
          opacity:open?1:0,
          pointerEvents:open?"auto":"none",
          transition:"opacity 0.3s",
        }}/>
      {/* Panel */}
      <aside style={{
        position:"fixed",top:0,left:0,height:"100%",zIndex:50,
        width:290,display:"flex",flexDirection:"column",
        background:"#fff",
        borderRight:`1.5px solid ${C.border}`,
        boxShadow:open?"4px 0 32px rgba(92,45,145,0.18)":"none",
        transform:open?"translateX(0)":"translateX(-100%)",
        transition:"transform 0.3s cubic-bezier(0.4,0,0.2,1)",
        overflowY:"auto",
      }}>
        {/* Header — gradient band */}
        <div style={{
          display:"flex",alignItems:"center",justifyContent:"space-between",
          padding:"14px 16px",flexShrink:0,
          background:"linear-gradient(135deg,#2D0854,#5C2D91)",
          position:"relative",overflow:"hidden",
        }}>
          {/* Decorative orb */}
          <div style={{position:"absolute",top:-20,right:-20,width:80,height:80,borderRadius:"50%",background:"rgba(0,184,159,0.2)",filter:"blur(10px)",pointerEvents:"none"}}/>
          <div style={{display:"flex",alignItems:"center",gap:10,position:"relative",zIndex:1}}>
            <div style={{width:38,height:38,borderRadius:12,background:"rgba(255,255,255,0.15)",border:"1.5px solid rgba(255,255,255,0.2)",display:"flex",alignItems:"center",justifyContent:"center"}}>
              <Logo size={28}/>
            </div>
            <div>
              <div style={{fontWeight:900,fontSize:14,color:"#fff"}}>MyTown 360</div>
              <div style={{fontSize:11,fontWeight:600,color:"rgba(0,184,159,0.9)"}}>EC · Bangalore ✦</div>
            </div>
          </div>
          <button onClick={onClose} style={{
            width:30,height:30,borderRadius:9,
            background:"rgba(255,255,255,0.12)",border:"1px solid rgba(255,255,255,0.18)",
            color:"rgba(255,255,255,0.8)",fontWeight:900,fontSize:15,cursor:"pointer",
            display:"flex",alignItems:"center",justifyContent:"center",position:"relative",zIndex:1,
          }}>✕</button>
        </div>

        {/* User card — glassy */}
        <div style={{
          margin:"12px 12px 4px",padding:"12px 14px",borderRadius:16,
          background:"linear-gradient(135deg,rgba(92,45,145,0.08),rgba(0,184,159,0.06))",
          border:`1.5px solid ${C.purple}22`,
          display:"flex",alignItems:"center",gap:10,
        }}>
          <div style={{
            width:42,height:42,borderRadius:12,
            background:"linear-gradient(135deg,#5C2D91,#8B5CF6)",
            display:"flex",alignItems:"center",justifyContent:"center",
            color:"#fff",fontWeight:900,fontSize:14,flexShrink:0,
            boxShadow:"0 3px 10px rgba(92,45,145,0.35)",
          }}>MT</div>
          <div style={{flex:1}}>
            <div style={{fontWeight:800,fontSize:13,color:C.text}}>Meena T.</div>
            <div style={{fontSize:11,color:C.mint,fontWeight:700}}>✅ Verified Resident</div>
          </div>
          <div style={{padding:"3px 10px",borderRadius:99,background:C.mintL,color:C.mint,fontWeight:800,fontSize:11,flexShrink:0,border:`1px solid ${C.mint}33`}}>EC P1</div>
        </div>

        {/* ── Actions (unique — not in bottom nav) ── */}
        <div style={{padding:"10px 12px 4px"}}>
          <div style={{fontSize:10,fontWeight:900,textTransform:"uppercase",letterSpacing:"0.12em",color:C.muted,marginBottom:8,paddingLeft:4}}>Quick Actions</div>
          {SIDEBAR_ACTIONS.map(item=>{
            const hl=item.highlight;
            return(
              <button key={item.id} onClick={()=>{ nav(item.id); onClose(); }}
                style={{
                  width:"100%",display:"flex",alignItems:"center",gap:10,
                  padding:"12px 12px",borderRadius:15,marginBottom:7,
                  border:`1.5px solid ${hl?"#00B89F44":C.border}`,
                  background:hl
                    ?"linear-gradient(135deg,rgba(0,184,159,0.08),rgba(0,184,159,0.04))"
                    :"#fff",
                  cursor:"pointer",textAlign:"left",
                  boxShadow:hl?"0 3px 14px rgba(0,184,159,0.14)":"0 2px 8px rgba(28,15,60,0.05)",
                }}>
                <div style={{
                  width:38,height:38,borderRadius:12,flexShrink:0,
                  background:hl?"linear-gradient(135deg,#008F7A,#00B89F)":`linear-gradient(135deg,${C.purple},${C.purpleL})`,
                  display:"flex",alignItems:"center",justifyContent:"center",
                  fontSize:18,
                  boxShadow:hl?"0 3px 10px rgba(0,184,159,0.35)":"0 3px 10px rgba(92,45,145,0.25)",
                }}>
                  {item.icon}
                </div>
                <div style={{flex:1}}>
                  <div style={{fontSize:13,fontWeight:800,color:hl?C.mint:C.text,lineHeight:1.2}}>{item.label}</div>
                  <div style={{fontSize:11,color:C.muted,marginTop:2}}>{item.sub}</div>
                </div>
                {hl
                  ? <span style={{fontSize:10,fontWeight:900,padding:"3px 8px",borderRadius:99,background:"linear-gradient(135deg,#008F7A,#00B89F)",color:"#fff",flexShrink:0,boxShadow:"0 2px 6px rgba(0,184,159,0.4)"}}>APPLY</span>
                  : <span style={{fontSize:16,color:C.muted,flexShrink:0,fontWeight:300}}>›</span>
                }
              </button>
            );
          })}
        </div>

        {/* Divider */}
        <div style={{margin:"4px 16px 8px",height:1,background:C.border}}/>

        {/* ── Quick Access grid ── */}
        <div style={{padding:"0 12px"}}>
          <div style={{fontSize:10,fontWeight:900,textTransform:"uppercase",letterSpacing:"0.12em",color:C.muted,marginBottom:8,paddingLeft:4}}>Quick Access</div>
          <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:7}}>
            {SIDEBAR_QUICK.map(item=>(
              <button key={item.label} onClick={()=>{ nav(item.id); onClose(); }}
                style={{
                  display:"flex",alignItems:"center",gap:8,
                  padding:"10px 10px",borderRadius:13,
                  background:"#fff",
                  border:`1.5px solid ${item.color}22`,
                  boxShadow:`0 2px 8px ${item.color}18`,
                  cursor:"pointer",textAlign:"left",
                }}>
                <div style={{
                  width:30,height:30,borderRadius:9,flexShrink:0,
                  background:`linear-gradient(135deg,${item.color},${item.color}BB)`,
                  display:"flex",alignItems:"center",justifyContent:"center",
                  fontSize:14,
                }}>{item.icon}</div>
                <span style={{fontSize:11,fontWeight:700,color:C.text,lineHeight:1.3}}>{item.label}</span>
              </button>
            ))}
          </div>
        </div>

        <div style={{flex:1}}/>

        {/* ── Emergency Helplines strip ── */}
        <div style={{padding:"8px 12px 4px"}}>
          <div style={{fontSize:10,fontWeight:900,textTransform:"uppercase",letterSpacing:"0.12em",color:C.muted,marginBottom:7,paddingLeft:4}}>Emergency Numbers</div>
          <div style={{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:5}}>
            {[{icon:"🚨",name:"Police",phone:"100",color:"#DC2626"},
              {icon:"🚑",name:"Ambulance",phone:"108",color:"#059669"},
              {icon:"🔥",name:"Fire",phone:"101",color:"#EA580C"}].map(h=>(
              <a key={h.phone} href={`tel:${h.phone}`}
                style={{display:"flex",flexDirection:"column",alignItems:"center",padding:"8px 4px",borderRadius:12,background:`${h.color}10`,border:`1.5px solid ${h.color}33`,textDecoration:"none",cursor:"pointer"}}>
                <span style={{fontSize:18}}>{h.icon}</span>
                <span style={{fontSize:11,fontWeight:900,color:h.color}}>{h.phone}</span>
                <span style={{fontSize:9,color:"#6B7280",fontWeight:600}}>{h.name}</span>
              </a>
            ))}
          </div>
          <button onClick={()=>{nav("helplines");onClose();}}
            style={{width:"100%",marginTop:7,padding:"8px",borderRadius:12,background:C.purpleFg,border:`1.5px solid ${C.border}`,color:C.purple,fontWeight:700,fontSize:12,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:5}}>
            📞 All Helpline Numbers ›
          </button>
        </div>

        {/* Admin Panel shortcut — hidden from public, accessed directly via /admin URL */}

        {/* Footer */}
        <div style={{padding:"12px 12px 20px",borderTop:`1.5px solid ${C.border}`,flexShrink:0,display:"flex",alignItems:"center",justifyContent:"space-between"}}>
          <button onClick={()=>{nav("landing");onClose();}}
            style={{display:"flex",alignItems:"center",gap:6,padding:"8px 14px",borderRadius:12,background:"#FFF0F1",color:C.coral,border:`1.5px solid ${C.coral}22`,fontWeight:700,fontSize:13,cursor:"pointer"}}>
            🚪 Sign Out
          </button>
          <div style={{textAlign:"right"}}>
            <div style={{fontWeight:700,fontSize:12,color:C.purple}}>MyTown 360</div>
            <div style={{fontSize:10,color:C.muted}}>v1.0 · EC Bangalore</div>
          </div>
        </div>
      </aside>
    </>
  );
}

// ─── SCREEN: Login ────────────────────────────────────────────────────────────
function LoginScreen({nav}){
  const [mode,setMode]=useState("email");        // "email" | "phone"
  const [identifier,setIdentifier]=useState(""); // email or phone value
  const [password,setPassword]=useState("");
  const [showPw,setShowPw]=useState(false);
  const [errs,setErrs]=useState({});
  const [submitted,setSubmitted]=useState(false);

  const setErr=(k,msg)=>setErrs(e=>msg?{...e,[k]:msg}:(({[k]:_,...rest})=>rest)(e));
  const idLabel = mode==="email"?"Email Address":"Mobile Number";
  const idPlaceholder = mode==="email"?"name@gmail.com":"98450 XXXXX";

  const validateId = v => mode==="email" ? vEmail(v) : vPhone(v);
  const filterInput = v => mode==="email" ? stripEmail(v) : stripPhone(v);

  const handleIdChange = e => {
    const v = filterInput(e.target.value);
    setIdentifier(v);
    if(errs.identifier) setErr("identifier", validateId(v));
  };
  const handlePwChange = e => {
    setPassword(e.target.value);
    if(errs.password) setErr("password", vPassword(e.target.value));
  };

  const handleSignIn = () => {
    const idErr = validateId(identifier);
    const pwErr = vPassword(password);
    const newErrs = {};
    if(idErr) newErrs.identifier = idErr;
    if(pwErr) newErrs.password = pwErr;
    if(Object.keys(newErrs).length){ setErrs(newErrs); return; }
    setSubmitted(true);
    // Simulate success — navigate to feed
    setTimeout(()=>nav("feed"), 900);
  };

  if(submitted) return(
    <div className="min-h-screen flex items-center justify-center" style={{background:C.surface}}>
      <div style={{textAlign:"center"}}>
        <div style={{fontSize:56,marginBottom:12}}>✅</div>
        <div style={{fontWeight:900,fontSize:18,color:C.text}}>Signing you in…</div>
        <div style={{fontSize:13,color:C.muted,marginTop:6}}>Welcome back to MyTown 360</div>
      </div>
    </div>
  );

  return(
    <div className="min-h-screen flex flex-col" style={{background:C.surface}}>
      {/* Header */}
      <div style={{
        background:"linear-gradient(135deg,#2D0854,#5C2D91)",
        padding:"14px 20px",
        display:"flex",alignItems:"center",gap:12,
        position:"relative",overflow:"hidden",
      }}>
        <div style={{position:"absolute",top:-20,right:-10,width:100,height:100,borderRadius:"50%",background:"rgba(0,184,159,0.18)",filter:"blur(14px)",pointerEvents:"none"}}/>
        <button onClick={()=>nav("landing")}
          style={{
            width:36,height:36,borderRadius:12,
            background:"rgba(255,255,255,0.12)",border:"1.5px solid rgba(255,255,255,0.18)",
            color:"#fff",fontWeight:900,fontSize:18,cursor:"pointer",
            display:"flex",alignItems:"center",justifyContent:"center",position:"relative",zIndex:1,
          }}>←</button>
        <div style={{position:"relative",zIndex:1}}>
          <div style={{fontWeight:900,fontSize:15,color:"#fff"}}>Sign in to MyTown 360</div>
          <div style={{fontSize:11,color:"rgba(0,184,159,0.85)"}}>mytown360.in ✦</div>
        </div>
      </div>

      {/* Body — centred, responsive */}
      <div style={{flex:1,display:"flex",alignItems:"flex-start",justifyContent:"center",padding:"28px 20px 32px"}}>
        <div style={{width:"100%",maxWidth:400}}>

          {/* Logo + welcome */}
          <div style={{textAlign:"center",marginBottom:28}}>
            <div className="mt-float" style={{
              width:80,height:80,borderRadius:24,margin:"0 auto 14px",
              background:"linear-gradient(135deg,#5C2D91,#7B4BB8)",
              display:"flex",alignItems:"center",justifyContent:"center",
              boxShadow:"0 8px 28px rgba(92,45,145,0.45)",
            }}>
              <Logo size={54}/>
            </div>
            <div style={{fontWeight:900,fontSize:22,color:C.text}}>Welcome Back!</div>
            <div style={{fontSize:13,color:C.muted,marginTop:4}}>Sign in to your verified neighbourhood account</div>
          </div>

          {/* Mode toggle */}
          <div style={{display:"flex",background:C.purpleFg,borderRadius:14,padding:4,marginBottom:20}}>
            {[["email","📧 Email"],["phone","📱 Phone"]].map(([m,l])=>(
              <button key={m} onClick={()=>{setMode(m);setIdentifier("");setErrs({});}}
                style={{flex:1,padding:"9px 0",borderRadius:10,fontWeight:800,fontSize:13,border:"none",cursor:"pointer",transition:"all 0.2s",
                  background:mode===m?"#fff":"transparent",
                  color:mode===m?C.purple:C.muted,
                  boxShadow:mode===m?`0 1px 6px ${C.purple}20`:"none"}}>
                {l}
              </button>
            ))}
          </div>

          {/* Identifier field */}
          <div style={{marginBottom:14}}>
            <label style={{display:"block",fontWeight:800,fontSize:13,color:C.text,marginBottom:6}}>{idLabel}</label>
            <div style={{display:"flex",alignItems:"center",gap:10,background:"#fff",border:`2px solid ${errs.identifier?C.coral:C.border}`,borderRadius:14,padding:"10px 14px"}}>
              <span style={{fontSize:16}}>{mode==="email"?"📧":"📱"}</span>
              <input style={{flex:1,fontSize:14,fontWeight:500,background:"transparent",border:"none",outline:"none",color:C.text}}
                type={mode==="email"?"email":"tel"}
                placeholder={idPlaceholder}
                value={identifier}
                onChange={handleIdChange}
                onBlur={()=>setErr("identifier",validateId(identifier))}
                autoComplete={mode==="email"?"email":"tel"}/>
            </div>
            {errs.identifier&&<p style={{fontSize:11,fontWeight:600,color:C.coral,marginTop:5}}>⚠ {errs.identifier}</p>}
          </div>

          {/* Password field */}
          <div style={{marginBottom:8}}>
            <label style={{display:"block",fontWeight:800,fontSize:13,color:C.text,marginBottom:6}}>Password</label>
            <div style={{display:"flex",alignItems:"center",gap:10,background:"#fff",border:`2px solid ${errs.password?C.coral:C.border}`,borderRadius:14,padding:"10px 14px"}}>
              <span style={{fontSize:16}}>🔒</span>
              <input style={{flex:1,fontSize:14,fontWeight:500,background:"transparent",border:"none",outline:"none",color:C.text}}
                type={showPw?"text":"password"}
                placeholder="Enter your password"
                value={password}
                onChange={handlePwChange}
                onBlur={()=>setErr("password",vPassword(password))}
                autoComplete="current-password"/>
              <button onClick={()=>setShowPw(p=>!p)}
                style={{fontSize:13,color:C.muted,background:"none",border:"none",cursor:"pointer",fontWeight:700,padding:0}}>
                {showPw?"Hide":"Show"}
              </button>
            </div>
            {errs.password&&<p style={{fontSize:11,fontWeight:600,color:C.coral,marginTop:5}}>⚠ {errs.password}</p>}
          </div>

          {/* Forgot password */}
          <div style={{textAlign:"right",marginBottom:22}}>
            <button onClick={()=>nav("forgot")}
              style={{fontSize:12,fontWeight:700,color:C.purple,background:"none",border:"none",cursor:"pointer",textDecoration:"underline"}}>
              Forgot Password?
            </button>
          </div>

          {/* Sign in button */}
          <button onClick={handleSignIn}
            style={{width:"100%",padding:"16px",borderRadius:18,fontWeight:900,fontSize:16,color:"#fff",border:"none",cursor:"pointer",
              background:"linear-gradient(135deg,#5C2D91,#7B4BB8,#9B6EE0)",
              boxShadow:`0 8px 28px rgba(92,45,145,0.5), inset 0 1px 0 rgba(255,255,255,0.12)`,
              letterSpacing:"0.01em",
            }}>
            Sign In →
          </button>

          {/* Divider */}
          <div style={{display:"flex",alignItems:"center",gap:10,margin:"20px 0"}}>
            <div style={{flex:1,height:1,background:C.border}}/>
            <span style={{fontSize:11,color:C.muted,fontWeight:600}}>OR</span>
            <div style={{flex:1,height:1,background:C.border}}/>
          </div>

          {/* Recovery / create account options */}
          <div style={{display:"flex",flexDirection:"column",gap:10}}>
            <button onClick={()=>nav("forgot")}
              style={{width:"100%",padding:"12px",borderRadius:14,fontWeight:700,fontSize:13,color:C.purple,background:C.purpleFg,border:`1.5px solid ${C.purple}28`,cursor:"pointer"}}>
              🔍 Forgot your Email / Phone?
            </button>
            <button onClick={()=>nav("signup")}
              style={{width:"100%",padding:"12px",borderRadius:14,fontWeight:700,fontSize:13,color:C.text,background:"#fff",border:`1.5px solid ${C.border}`,cursor:"pointer"}}>
              New here? Create an account →
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── SCREEN: Forgot Account Recovery ─────────────────────────────────────────
function ForgotScreen({nav}){
  const [step,setStep]=useState(0);    // 0=choose method, 1=enter details, 2=otp, 3=success
  const [method,setMethod]=useState(""); // "email" | "phone"
  const [value,setValue]=useState("");
  const [otp,setOtp]=useState(["","","","","",""]);
  const [recoverType,setRecoverType]=useState("password"); // "password" | "userid"
  const [errs,setErrs]=useState({});
  const setErr=(k,msg)=>setErrs(e=>msg?{...e,[k]:msg}:(({[k]:_,...rest})=>rest)(e));

  const validate=()=>{
    const err = method==="email"?vEmail(value):vPhone(value);
    if(err){setErr("value",err);return false;}
    return true;
  };

  const handleSend=()=>{
    if(!method){setErr("method","Please choose a recovery method");return;}
    if(!validate()) return;
    setStep(2);
  };

  const handleOtpChange=(i,v)=>{
    const d=v.replace(/\D/,"").slice(0,1);
    const next=[...otp]; next[i]=d; setOtp(next);
    if(d&&i<5){ const el=document.getElementById(`otp-${i+1}`); if(el) el.focus(); }
  };

  const handleVerify=()=>{
    if(otp.join("").length<6){setErr("otp","Enter all 6 digits");return;}
    setStep(3);
  };

  const Screen0=(
    <div>
      <div style={{textAlign:"center",marginBottom:24}}>
        <div style={{fontSize:44,marginBottom:8}}>🔐</div>
        <div style={{fontWeight:900,fontSize:18,color:C.text}}>Recover Your Account</div>
        <div style={{fontSize:13,color:C.muted,marginTop:6}}>What would you like to recover?</div>
      </div>
      {/* Recover type */}
      <div style={{display:"flex",gap:10,marginBottom:20}}>
        {[["password","🔑 Password"],["userid","🪪 Email / Phone"]].map(([t,l])=>(
          <button key={t} onClick={()=>setRecoverType(t)}
            style={{flex:1,padding:"12px 8px",borderRadius:14,fontWeight:700,fontSize:12,border:`2px solid ${recoverType===t?C.purple:C.border}`,
              background:recoverType===t?C.purpleFg:"#fff",color:recoverType===t?C.purple:C.muted,cursor:"pointer"}}>
            {l}
          </button>
        ))}
      </div>
      <div style={{fontSize:13,fontWeight:700,color:C.text,marginBottom:12}}>How do you want to receive the OTP?</div>
      <div style={{display:"flex",flexDirection:"column",gap:10,marginBottom:20}}>
        {[["email","📧","Via Email Address","Enter your registered email"],["phone","📱","Via Mobile Number","Enter your registered phone"]].map(([m,ic,title,sub])=>(
          <button key={m} onClick={()=>{setMethod(m);setValue("");setErrs({});}}
            style={{display:"flex",alignItems:"center",gap:14,padding:"14px 16px",borderRadius:16,border:`2px solid ${method===m?C.purple:C.border}`,
              background:method===m?C.purpleFg:"#fff",cursor:"pointer",textAlign:"left"}}>
            <span style={{fontSize:22}}>{ic}</span>
            <div>
              <div style={{fontWeight:800,fontSize:13,color:method===m?C.purple:C.text}}>{title}</div>
              <div style={{fontSize:11,color:C.muted}}>{sub}</div>
            </div>
            {method===m&&<span style={{marginLeft:"auto",color:C.purple,fontWeight:900}}>✓</span>}
          </button>
        ))}
      </div>
      {errs.method&&<p style={{fontSize:11,color:C.coral,fontWeight:600,marginBottom:10}}>⚠ {errs.method}</p>}
      {method&&(
        <div style={{marginBottom:16}}>
          <label style={{display:"block",fontWeight:800,fontSize:13,color:C.text,marginBottom:6}}>
            {method==="email"?"Your registered email":"Your registered mobile number"}
          </label>
          <div style={{display:"flex",alignItems:"center",gap:10,background:"#fff",border:`2px solid ${errs.value?C.coral:C.border}`,borderRadius:14,padding:"10px 14px"}}>
            <span style={{fontSize:16}}>{method==="email"?"📧":"📱"}</span>
            <input style={{flex:1,fontSize:14,fontWeight:500,background:"transparent",border:"none",outline:"none",color:C.text}}
              type={method==="email"?"email":"tel"}
              placeholder={method==="email"?"name@gmail.com":"98450 XXXXX"}
              value={value}
              onChange={e=>{ const v=method==="email"?stripEmail(e.target.value):stripPhone(e.target.value); setValue(v); if(errs.value)setErr("value",method==="email"?vEmail(v):vPhone(v)); }}
              onBlur={()=>validate()}/>
          </div>
          {errs.value&&<p style={{fontSize:11,fontWeight:600,color:C.coral,marginTop:5}}>⚠ {errs.value}</p>}
        </div>
      )}
      <button onClick={handleSend}
        style={{width:"100%",padding:"14px",borderRadius:16,fontWeight:900,fontSize:15,color:"#fff",border:"none",cursor:"pointer",
          background:`linear-gradient(135deg,${C.purple},${C.purpleL})`}}>
        Send OTP →
      </button>
    </div>
  );

  const Screen2=(
    <div>
      <div style={{textAlign:"center",marginBottom:28}}>
        <div style={{fontSize:44,marginBottom:8}}>{method==="email"?"📧":"📱"}</div>
        <div style={{fontWeight:900,fontSize:18,color:C.text}}>Enter Verification Code</div>
        <div style={{fontSize:13,color:C.muted,marginTop:6}}>
          We sent a 6-digit OTP to {method==="email"?"your email":"your mobile"}<br/>
          <span style={{fontWeight:700,color:C.purple}}>{value}</span>
        </div>
      </div>
      <div style={{display:"flex",gap:8,justifyContent:"center",marginBottom:8}}>
        {otp.map((digit,i)=>(
          <input key={i} id={`otp-${i}`}
            style={{width:44,height:52,textAlign:"center",fontSize:20,fontWeight:900,borderRadius:12,border:`2px solid ${errs.otp?C.coral:digit?C.purple:C.border}`,outline:"none",color:C.text}}
            maxLength={1} value={digit}
            onChange={e=>handleOtpChange(i,e.target.value)}
            onKeyDown={e=>{if(e.key==="Backspace"&&!digit&&i>0){const el=document.getElementById(`otp-${i-1}`);if(el)el.focus();}}}/>
        ))}
      </div>
      {errs.otp&&<p style={{fontSize:11,fontWeight:600,color:C.coral,marginBottom:8,textAlign:"center"}}>⚠ {errs.otp}</p>}
      <p style={{textAlign:"center",fontSize:12,color:C.muted,marginBottom:20}}>Didn't receive it? <button onClick={()=>{}} style={{color:C.purple,fontWeight:700,background:"none",border:"none",cursor:"pointer"}}>Resend OTP</button></p>
      <button onClick={handleVerify}
        style={{width:"100%",padding:"14px",borderRadius:16,fontWeight:900,fontSize:15,color:"#fff",border:"none",cursor:"pointer",
          background:`linear-gradient(135deg,${C.mint},#00967E)`}}>
        Verify & Continue
      </button>
    </div>
  );

  const Screen3=(
    <div style={{textAlign:"center"}}>
      <div style={{fontSize:56,marginBottom:12}}>🎉</div>
      <div style={{fontWeight:900,fontSize:20,color:C.text,marginBottom:8}}>Verified!</div>
      <div style={{fontSize:13,color:C.muted,marginBottom:24}}>
        {recoverType==="password"?"You can now set a new password for your account.":"Your registered email / phone has been sent to you."}
      </div>
      {recoverType==="password"&&(
        <div style={{marginBottom:20,textAlign:"left"}}>
          <label style={{display:"block",fontWeight:800,fontSize:13,color:C.text,marginBottom:6}}>New Password</label>
          <div style={{display:"flex",alignItems:"center",gap:10,background:"#fff",border:`2px solid ${C.border}`,borderRadius:14,padding:"10px 14px"}}>
            <span style={{fontSize:16}}>🔒</span>
            <input style={{flex:1,fontSize:14,background:"transparent",border:"none",outline:"none",color:C.text}} type="password" placeholder="Min. 6 characters"/>
          </div>
        </div>
      )}
      <button onClick={()=>nav("login")}
        style={{width:"100%",padding:"14px",borderRadius:16,fontWeight:900,fontSize:15,color:"#fff",border:"none",cursor:"pointer",
          background:`linear-gradient(135deg,${C.purple},${C.purpleL})`}}>
        {recoverType==="password"?"Save & Sign In →":"Go to Sign In →"}
      </button>
    </div>
  );

  return(
    <div className="min-h-screen flex flex-col" style={{background:C.surface}}>
      {/* Header */}
      <div style={{background:"#fff",borderBottom:`1px solid ${C.border}`,padding:"14px 20px",display:"flex",alignItems:"center",gap:12}}>
        <button onClick={()=>step===0?nav("login"):setStep(s=>s-1)}
          style={{width:36,height:36,borderRadius:12,background:C.purpleFg,color:C.purple,fontWeight:900,fontSize:18,border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"}}>←</button>
        <div>
          <div style={{fontWeight:900,fontSize:15,color:C.text}}>Account Recovery</div>
          <div style={{fontSize:11,color:C.muted}}>MyTown 360 · mytown360.in</div>
        </div>
        {/* Step dots */}
        <div style={{marginLeft:"auto",display:"flex",gap:5}}>
          {[0,2,3].map((s,i)=>(
            <div key={i} style={{width:step===s?18:8,height:8,borderRadius:99,transition:"width 0.2s",
              background:step>s?C.mint:step===s?C.purple:C.border}}/>
          ))}
        </div>
      </div>

      <div style={{flex:1,display:"flex",alignItems:"flex-start",justifyContent:"center",padding:"28px 20px 32px"}}>
        <div style={{width:"100%",maxWidth:400}}>
          {step===0&&Screen0}
          {step===2&&Screen2}
          {step===3&&Screen3}
        </div>
      </div>
    </div>
  );
}

// ─── SCREEN: Landing ─────────────────────────────────────────────────────────
function LandingScreen({nav}){
  return(
    <div style={{minHeight:"100vh",display:"flex",flexDirection:"column",alignItems:"center",background:"#0E0520",overflow:"hidden"}}>
      <div style={{width:"100%",maxWidth:480,display:"flex",flexDirection:"column",minHeight:"100vh",position:"relative"}}>

        {/* ── Animated mesh gradient background ── */}
        <div style={{position:"fixed",inset:0,zIndex:0,overflow:"hidden",pointerEvents:"none"}}>
          {/* Main gradient layer */}
          <div style={{position:"absolute",inset:0,background:"linear-gradient(160deg,#12003A 0%,#2D0854 30%,#1A0636 60%,#001F20 100%)"}}/>
          {/* Orb 1 — purple */}
          <div className="mt-blob" style={{
            position:"absolute",top:"-15%",left:"-10%",
            width:400,height:400,borderRadius:"50%",
            background:"radial-gradient(circle,rgba(92,45,145,0.7) 0%,rgba(92,45,145,0) 70%)",
            filter:"blur(20px)",
          }}/>
          {/* Orb 2 — mint */}
          <div className="mt-blob2" style={{
            position:"absolute",bottom:"-5%",right:"-10%",
            width:360,height:360,borderRadius:"50%",
            background:"radial-gradient(circle,rgba(0,184,159,0.5) 0%,rgba(0,184,159,0) 70%)",
            filter:"blur(24px)",
          }}/>
          {/* Orb 3 — coral accent */}
          <div style={{
            position:"absolute",top:"40%",right:"5%",
            width:200,height:200,borderRadius:"50%",
            background:"radial-gradient(circle,rgba(255,107,122,0.25) 0%,rgba(255,107,122,0) 70%)",
            filter:"blur(16px)",
            animation:"blobDrift 15s 1s ease-in-out infinite",
          }}/>
          {/* Fine dot grid overlay */}
          <div style={{
            position:"absolute",inset:0,
            backgroundImage:"radial-gradient(rgba(255,255,255,0.06) 1px,transparent 1px)",
            backgroundSize:"28px 28px",
          }}/>
        </div>

        {/* ── Hero section ── */}
        <div style={{position:"relative",zIndex:1,padding:"56px 24px 28px",textAlign:"center"}}>

          {/* Logo with glow ring */}
          <div className="mt-fade-up" style={{display:"flex",justifyContent:"center",marginBottom:22}}>
            <div className="mt-float mt-glow-ring" style={{
              width:96,height:96,borderRadius:28,
              background:"linear-gradient(135deg,rgba(255,255,255,0.18),rgba(255,255,255,0.05))",
              backdropFilter:"blur(12px)",border:"1.5px solid rgba(255,255,255,0.2)",
              display:"flex",alignItems:"center",justifyContent:"center",
              boxShadow:"0 8px 32px rgba(0,184,159,0.3)",
            }}>
              <Logo size={64}/>
            </div>
          </div>

          {/* Brand name with gradient text */}
          <div className="mt-fade-up-2">
            <h1 style={{
              fontSize:38,fontWeight:900,margin:"0 0 4px",
              background:"linear-gradient(135deg,#fff 20%,#D4BCFF 60%,#00B89F 100%)",
              WebkitBackgroundClip:"text",WebkitTextFillColor:"transparent",backgroundClip:"text",
              lineHeight:1.1,letterSpacing:"-0.02em",
            }}>MyTown 360</h1>
            <p style={{fontSize:13,fontWeight:700,color:"rgba(0,184,159,0.9)",margin:"0 0 10px",letterSpacing:"0.08em"}}>
              ✦ mytown360.in ✦
            </p>
            <p style={{fontSize:16,color:"rgba(255,255,255,0.8)",margin:"0 0 4px",fontWeight:600}}>
              Your Real Neighbourhood, Online.
            </p>
            <p style={{fontSize:12,color:"rgba(255,255,255,0.45)",margin:0}}>
              Electronic City · Hebbagodi · Bommasandra &amp; beyond
            </p>
          </div>
        </div>

        {/* ── Feature cards — glassy 2×2 grid ── */}
        <div className="mt-fade-up-3" style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10,padding:"0 18px 20px",position:"relative",zIndex:1}}>
          {[
            {col:"#7B4BB8",ic:"🛡️",t:"ID Verified",  s:"Real neighbours only",  grad:"linear-gradient(135deg,rgba(92,45,145,0.5),rgba(123,75,184,0.2))"},
            {col:"#00B89F",ic:"📍",t:"Hyper-Local",  s:"Your exact sub-area",   grad:"linear-gradient(135deg,rgba(0,184,159,0.45),rgba(0,150,126,0.2))"},
            {col:"#FF6B7A",ic:"🔒",t:"Safe Space",   s:"Moderated & trusted",   grad:"linear-gradient(135deg,rgba(255,107,122,0.4),rgba(232,55,74,0.15))"},
            {col:"#A78BFA",ic:"🗺️",t:"Area Map",     s:"EC & surroundings",     grad:"linear-gradient(135deg,rgba(167,139,250,0.4),rgba(107,127,240,0.15))"},
          ].map(({col,ic,t,s,grad},idx)=>(
            <div key={t} style={{
              borderRadius:20,padding:"16px 12px 14px",textAlign:"center",
              background:grad,
              backdropFilter:"blur(16px)",
              border:"1px solid rgba(255,255,255,0.12)",
              boxShadow:"0 4px 24px rgba(0,0,0,0.25)",
            }}>
              <div style={{
                width:44,height:44,borderRadius:14,margin:"0 auto 10px",
                background:"rgba(255,255,255,0.12)",
                display:"flex",alignItems:"center",justifyContent:"center",
                fontSize:22,
                border:"1px solid rgba(255,255,255,0.15)",
              }}>{ic}</div>
              <div style={{fontSize:13,fontWeight:900,color:"#fff",marginBottom:3}}>{t}</div>
              <div style={{fontSize:11,color:"rgba(255,255,255,0.55)"}}>{s}</div>
            </div>
          ))}
        </div>

        {/* ── Stats bar — glassmorphism card ── */}
        <div className="mt-fade-up-3" style={{
          margin:"0 18px 24px",borderRadius:22,padding:"18px 12px",
          display:"flex",justifyContent:"space-around",alignItems:"center",
          background:"linear-gradient(135deg,rgba(255,255,255,0.12),rgba(255,255,255,0.04))",
          backdropFilter:"blur(20px)",
          border:"1.5px solid rgba(255,255,255,0.15)",
          boxShadow:"0 8px 32px rgba(0,0,0,0.3), inset 0 1px 0 rgba(255,255,255,0.1)",
          position:"relative",zIndex:1,
        }}>
          {[["2,400+","Verified Residents","#D4BCFF"],["160+","Apartments","#6EE7DF"],["21","Areas Covered","#FBB17B"]].map(([n,l,col])=>(
            <div key={l} style={{textAlign:"center",flex:1}}>
              <div style={{
                fontSize:22,fontWeight:900,
                background:`linear-gradient(135deg,${col},#fff)`,
                WebkitBackgroundClip:"text",WebkitTextFillColor:"transparent",backgroundClip:"text",
              }}>{n}</div>
              <div style={{fontSize:10,fontWeight:600,color:"rgba(255,255,255,0.5)",marginTop:2}}>{l}</div>
            </div>
          ))}
          {/* Dividers */}
          <div style={{position:"absolute",left:"33.3%",top:"20%",bottom:"20%",width:1,background:"rgba(255,255,255,0.12)"}}/>
          <div style={{position:"absolute",left:"66.6%",top:"20%",bottom:"20%",width:1,background:"rgba(255,255,255,0.12)"}}/>
        </div>

        {/* ── Trust chips ── */}
        <div className="mt-fade-up-4" style={{display:"flex",justifyContent:"center",gap:8,flexWrap:"wrap",padding:"0 18px 8px",position:"relative",zIndex:1}}>
          {["🏛️ Govt-verified","📵 Zero spam","🔐 Privacy first","🆓 Always free"].map(chip=>(
            <span key={chip} style={{
              padding:"5px 12px",borderRadius:99,fontSize:11,fontWeight:700,
              background:"rgba(255,255,255,0.08)",border:"1px solid rgba(255,255,255,0.14)",
              color:"rgba(255,255,255,0.65)",
            }}>{chip}</span>
          ))}
        </div>

        {/* ── CTA buttons ── */}
        <div className="mt-fade-up-4" style={{marginTop:"auto",padding:"20px 18px 42px",display:"flex",flexDirection:"column",gap:12,position:"relative",zIndex:1}}>
          <button onClick={()=>nav("signup")}
            style={{
              width:"100%",padding:"17px",borderRadius:20,fontWeight:900,fontSize:17,
              color:"#fff",border:"none",cursor:"pointer",
              background:"linear-gradient(135deg,#5C2D91,#7B4BB8,#9B6EE0)",
              backgroundSize:"200% 200%",
              boxShadow:"0 10px 36px rgba(92,45,145,0.65), 0 1px 0 rgba(255,255,255,0.15) inset",
              letterSpacing:"0.01em",
            }}>
            Join My Neighbourhood →
          </button>
          <button onClick={()=>nav("login")}
            style={{
              width:"100%",padding:"15px",borderRadius:20,fontWeight:700,fontSize:14,
              border:"1.5px solid rgba(255,255,255,0.2)",cursor:"pointer",
              background:"rgba(255,255,255,0.06)",
              backdropFilter:"blur(12px)",
              color:"rgba(255,255,255,0.85)",
            }}>
            Already a member? Sign in
          </button>
          <p style={{textAlign:"center",fontSize:11,color:"rgba(255,255,255,0.35)",margin:0}}>
            🔒 Government ID required · Your data stays safe
          </p>
        </div>

      </div>
    </div>
  );
}

// ─── SCREEN: Signup with SmartInput ─────────────────────────────────────────
const STEPS=["About You","Your Home","Identity","Selfie"];
const BIZ_STEPS=["Account Type","Business Info","Documents","Verification"];
const BIZ_TYPES=["Restaurant / Food","Grocery / Supermart","Services / Repairs","Medical / Pharmacy","Education / Coaching","Beauty / Wellness","Retail / Shop","Other"];
const ID_TYPES=["Aadhaar Card","Voter ID","Passport","Driving Licence"];

function SignupScreen({nav}){
  const [acctType,setAcctType]=useState(""); // "personal" | "business"
  const [step,setStep]=useState(0);          // 0=choose type; personal:1-4; business:1-4
  const [form,setForm]=useState({name:"",email:"",phone:"",area:"",apartment:"",street:"",flat:""});
  const [idType,setIdType]=useState("Aadhaar Card");
  const [uploaded,setUploaded]=useState({});
  const [bizForm,setBizForm]=useState({bizName:"",bizType:"",ownerName:"",phone:"",area:""});
  const [hasLicense,setHasLicense]=useState(null); // null | true | false
  const [errs,setErrs]=useState({});
  const set=(k,v)=>setForm(f=>({...f,[k]:v}));
  const setBiz=(k,v)=>setBizForm(f=>({...f,[k]:v}));
  const setErr=(k,msg)=>setErrs(e=>msg?{...e,[k]:msg}:(({[k]:_,...rest})=>rest)(e));
  const blur=(k,val,fn)=>setErr(k,fn(val));

  /* Returns null if step is valid, or an errors object if not */
  const validateStep=()=>{
    const e={};
    if(!isBiz&&step===1){
      const n=vName(form.name); if(n) e.name=n;
      const em=vEmail(form.email); if(em) e.email=em;
      const p=vPhone(form.phone); if(p) e.phone=p;
    }
    if(!isBiz&&step===2){
      const a=vArea(form.area); if(a) e.area=a;
      const ap=vApt(form.apartment); if(ap) e.apartment=ap;
      const fl=vFlat(form.flat); if(fl) e.flat=fl;
    }
    if(!isBiz&&step===3){
      if(!uploaded.id) e.id="Government ID is required";
      if(!uploaded.address) e.address="Address proof is required";
    }
    if(isBiz&&step===1){
      const bn=vBizName(bizForm.bizName); if(bn) e.bizName=bn;
      const on=vName(bizForm.ownerName); if(on) e.ownerName=on;
      const bp=vPhone(bizForm.phone); if(bp) e.phone=bp;
      if(!bizForm.bizType) e.bizType="Please select a business category";
    }
    if(isBiz&&step===2){
      const ba=vArea(bizForm.area); if(ba) e.bizArea=ba;
      if(!uploaded.bizFront) e.bizFront="Live photo of business front is required";
    }
    if(isBiz&&step===3){
      if(hasLicense===null) e.hasLicense="Please indicate if you have a license";
      else if(hasLicense&&!uploaded.bizLicense) e.bizLicense="Please upload your business license";
      else if(!hasLicense&&!uploaded.bizDoc) e.bizDoc="Please upload a business document";
      if(!uploaded.ownerId) e.ownerId="Owner ID is required";
    }
    return Object.keys(e).length?e:null;
  };
  const handleContinue=()=>{
    const e=validateStep();
    if(e){setErrs(prev=>({...prev,...e}));return;}
    setStep(s=>s+1);
  };

  const selectedArea=form.area.replace(/\s*\(PIN:.*\)/,"").trim();
  const aptOptions=selectedArea&&APT_BY_AREA[selectedArea] ? APT_BY_AREA[selectedArea] : ALL_APTS;

  const isBiz=acctType==="business";
  const steps=isBiz?BIZ_STEPS:STEPS;
  const maxStep=steps.length;

  // ── Step 0: Choose account type ──
  if(step===0) return(
    <div style={{minHeight:"100vh",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:"24px 20px",background:C.surface,position:"relative",overflow:"hidden"}}>
      {/* Subtle background orbs */}
      <div style={{position:"absolute",top:-60,left:-60,width:220,height:220,borderRadius:"50%",background:`radial-gradient(circle,${C.purple}18,transparent 70%)`,pointerEvents:"none"}}/>
      <div style={{position:"absolute",bottom:-40,right:-40,width:180,height:180,borderRadius:"50%",background:`radial-gradient(circle,${C.mint}15,transparent 70%)`,pointerEvents:"none"}}/>

      <div style={{width:"100%",maxWidth:380,position:"relative",zIndex:1}}>
        <div className="mt-fade-up" style={{textAlign:"center",marginBottom:32}}>
          <div style={{
            width:72,height:72,borderRadius:22,margin:"0 auto 16px",
            background:`linear-gradient(135deg,#5C2D91,#7B4BB8)`,
            display:"flex",alignItems:"center",justifyContent:"center",fontSize:34,
            boxShadow:"0 8px 28px rgba(92,45,145,0.4)",
          }}>🏘️</div>
          <div style={{fontWeight:900,fontSize:22,color:C.text,letterSpacing:"-0.01em"}}>Join MyTown 360</div>
          <div style={{fontSize:13,color:C.muted,marginTop:5}}>Choose your account type to get started</div>
        </div>
        <div className="mt-fade-up-2" style={{display:"flex",flexDirection:"column",gap:12}}>
          {/* Personal */}
          <button onClick={()=>{setAcctType("personal");setStep(1);}}
            style={{
              display:"flex",alignItems:"center",gap:16,padding:"18px 20px",borderRadius:20,
              border:`2px solid ${C.purple}18`,background:"#fff",cursor:"pointer",textAlign:"left",
              boxShadow:"0 4px 20px rgba(92,45,145,0.08)",
              transition:"transform 0.15s, box-shadow 0.15s",
            }}>
            <div style={{
              width:54,height:54,borderRadius:16,
              background:`linear-gradient(135deg,${C.purpleFg},#E5D6FF)`,
              border:`1.5px solid ${C.purple}22`,
              display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,fontSize:26,
            }}>🧑</div>
            <div style={{flex:1}}>
              <div style={{fontWeight:900,fontSize:15,color:C.text}}>Personal / Resident Account</div>
              <div style={{fontSize:12,color:C.muted,marginTop:2}}>For area residents. Share posts, attend events, vote in elections.</div>
              <div style={{marginTop:7,display:"flex",gap:5}}>
                <span style={{fontSize:10,fontWeight:800,padding:"3px 8px",borderRadius:99,background:C.mintL,color:C.mint,border:`1px solid ${C.mint}30`}}>Free</span>
                <span style={{fontSize:10,fontWeight:800,padding:"3px 8px",borderRadius:99,background:C.purpleFg,color:C.purple,border:`1px solid ${C.purple}20`}}>Govt ID required</span>
              </div>
            </div>
            <span style={{fontSize:20,color:C.purpleL,fontWeight:900}}>›</span>
          </button>
          {/* Business */}
          <button onClick={()=>{setAcctType("business");setStep(1);}}
            style={{
              display:"flex",alignItems:"center",gap:16,padding:"18px 20px",borderRadius:20,
              border:`2px solid ${C.marigold}44`,background:"linear-gradient(135deg,#FFFBF0,#FFF7E6)",cursor:"pointer",textAlign:"left",
              boxShadow:"0 4px 20px rgba(255,179,71,0.12)",
            }}>
            <div style={{
              width:54,height:54,borderRadius:16,
              background:`linear-gradient(135deg,${C.marigoldL},#FFE5B0)`,
              border:`1.5px solid ${C.marigold}44`,
              display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,fontSize:26,
            }}>🏪</div>
            <div style={{flex:1}}>
              <div style={{fontWeight:900,fontSize:15,color:C.text}}>Business Account</div>
              <div style={{fontSize:12,color:C.muted,marginTop:2}}>For local businesses. Reach verified neighbourhood residents.</div>
              <div style={{marginTop:7,display:"flex",gap:5}}>
                <span style={{fontSize:10,fontWeight:800,padding:"3px 8px",borderRadius:99,background:C.marigoldL,color:"#92400E",border:`1px solid ${C.marigold}40`}}>Promotions available</span>
                <span style={{fontSize:10,fontWeight:800,padding:"3px 8px",borderRadius:99,background:"#FEF2F2",color:C.crimson,border:"1px solid #FCA5A533"}}>Verification mandatory</span>
              </div>
            </div>
            <span style={{fontSize:20,color:C.marigold,fontWeight:900}}>›</span>
          </button>
        </div>
        <button onClick={()=>nav("landing")} style={{width:"100%",marginTop:16,padding:"11px",borderRadius:14,background:"transparent",color:C.muted,fontWeight:700,fontSize:13,border:`1.5px solid ${C.border}`,cursor:"pointer"}}>← Back to Home</button>
      </div>
    </div>
  );

  return(
    <div className="min-h-screen flex flex-col" style={{background:C.surface}}>
      {/* Header */}
      <div style={{
        padding:"12px 16px",display:"flex",alignItems:"center",gap:12,
        background:`linear-gradient(135deg,${isBiz?"#3A2000,#7A4800":"#2D0854,#5C2D91"})`,
        position:"relative",overflow:"hidden",
      }}>
        <div style={{position:"absolute",top:-20,right:-10,width:80,height:80,borderRadius:"50%",background:isBiz?"rgba(255,179,71,0.2)":"rgba(0,184,159,0.18)",filter:"blur(12px)",pointerEvents:"none"}}/>
        <button onClick={()=>step>1?setStep(s=>s-1):setStep(0)}
          style={{
            width:34,height:34,borderRadius:10,
            background:"rgba(255,255,255,0.12)",border:"1.5px solid rgba(255,255,255,0.18)",
            color:"#fff",fontWeight:900,fontSize:16,cursor:"pointer",
            display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,position:"relative",zIndex:1,
          }}>←</button>
        <div style={{flex:1,position:"relative",zIndex:1}}>
          <div style={{display:"flex",alignItems:"center",gap:7}}>
            <span style={{fontSize:14}}>{isBiz?"🏪":"🧑"}</span>
            <div style={{fontWeight:900,fontSize:14,color:"#fff"}}>{isBiz?"Business Account":"Personal Account"}</div>
          </div>
          <div style={{fontSize:11,color:"rgba(255,255,255,0.6)",marginTop:1}}>{steps[step-1]}</div>
        </div>
        {/* Step dots */}
        <div style={{display:"flex",gap:5,alignItems:"center",position:"relative",zIndex:1}}>
          {steps.map((_,i)=>(
            <div key={i} style={{
              borderRadius:99,transition:"all 0.25s",
              width:i+1===step?18:7,height:7,
              background:i+1<step
                ? C.mint
                : i+1===step
                  ? (isBiz?C.marigold:"rgba(255,255,255,0.95)")
                  : "rgba(255,255,255,0.25)",
            }}/>
          ))}
        </div>
      </div>

      <div className="flex-1 px-5 py-6 max-w-sm mx-auto w-full">

        {/* ══════════════ PERSONAL FLOW ══════════════ */}
        {!isBiz&&step===1&&(
          <div className="space-y-4">
            <div className="rounded-2xl p-4" style={{background:C.purpleFg}}>
              <p className="text-sm font-semibold" style={{color:C.purple}}>👋 Fill your details exactly as they appear on your government ID.</p>
            </div>
            {[["Full Name","name","Priya Venkataraman","🪪",vName,stripName],["Email Address","email","name@gmail.com","📧",vEmail,stripEmail],["Mobile Number","phone","98450 XXXXX","📱",vPhone,stripPhone]].map(([l,k,p,ic,vfn,sfn])=>(
              <div key={k}>
                <label className="text-sm font-black mb-1.5 block" style={{color:C.text}}>{l}</label>
                <div className="flex items-center rounded-xl px-3 py-2.5 gap-2" style={{background:"#fff",border:`2px solid ${errs[k]?C.coral:C.border}`}}>
                  <span className="text-base">{ic}</span>
                  <input className="flex-1 text-sm font-medium bg-transparent focus:outline-none" style={{color:C.text}}
                    type={k==="email"?"email":k==="phone"?"tel":"text"}
                    placeholder={p} value={form[k]}
                    onChange={e=>{const v=sfn(e.target.value);set(k,v);if(errs[k])setErr(k,vfn(v));}}
                    onBlur={()=>blur(k,form[k],vfn)}/>
                </div>
                {errs[k]&&<p className="text-xs mt-1 font-semibold" style={{color:C.coral}}>⚠ {errs[k]}</p>}
              </div>
            ))}
          </div>
        )}
        {!isBiz&&step===2&&(
          <div className="space-y-5">
            <div className="rounded-2xl p-4" style={{background:C.mintL,border:`1.5px solid ${C.mint}30`}}>
              <p className="text-sm font-semibold" style={{color:C.mint}}>📍 Start typing to see suggestions — or enter your own if not listed.</p>
            </div>
            <div>
              <SmartInput label="Area / Locality" placeholder="e.g. Electronic City Phase 1…" groupedOptions={AREA_GROUPS} value={form.area}
                onChange={(v,fromDropdown)=>{set("area",v);set("apartment","");fromDropdown?setErr("area",null):setErr("area",vArea(v));}} icon="📍"
                filterFn={stripAddr} error={errs.area}/>
              {errs.area&&<p className="text-xs mt-1 font-semibold" style={{color:C.coral}}>⚠ {errs.area}</p>}
            </div>
            <div>
              <SmartInput label="Apartment / Society" placeholder={selectedArea?`Search in ${selectedArea}…`:"e.g. Prestige Sunrise Park…"} options={aptOptions} value={form.apartment}
                onChange={(v,fromDropdown)=>{set("apartment",v);fromDropdown?setErr("apartment",null):setErr("apartment",vApt(v));}} icon="🏢"
                filterFn={stripAddr} error={errs.apartment}/>
              {selectedArea&&APT_BY_AREA[selectedArea]&&(<p className="text-xs mt-1 font-semibold" style={{color:C.mint}}>✦ {APT_BY_AREA[selectedArea].length} apartments listed in {selectedArea}</p>)}
              {errs.apartment&&<p className="text-xs mt-1 font-semibold" style={{color:C.coral}}>⚠ {errs.apartment}</p>}
            </div>
            <SmartInput label="Street / Nearby Landmark" placeholder="e.g. Neeladri Road, Infosys Gate…" icon="🛣️" filterFn={stripAddr}
              groupedOptions={[...STREET_GROUPS,{group:"Landmarks & Institutions",icon:"🏛️",items:LANDMARKS}]}
              value={form.street} onChange={(v)=>set("street",v)}/>
            <div>
              <label className="text-sm font-black mb-1.5 block" style={{color:C.text}}>Flat / Door No.</label>
              <div className="flex items-center rounded-xl px-3 py-2.5 gap-2" style={{background:"#fff",border:`2px solid ${errs.flat?C.coral:C.border}`}}>
                <span className="text-base">🚪</span>
                <input className="flex-1 text-sm font-medium bg-transparent focus:outline-none" style={{color:C.text}} placeholder="e.g. B-302, Tower 4 / Flat 1201" value={form.flat}
                  onChange={e=>{const v=stripAddr(e.target.value);set("flat",v);if(errs.flat)setErr("flat",vFlat(v));}}
                  onBlur={()=>blur("flat",form.flat,vFlat)}/>
              </div>
              {errs.flat&&<p className="text-xs mt-1 font-semibold" style={{color:C.coral}}>⚠ {errs.flat}</p>}
            </div>
            {form.area&&form.apartment&&(
              <div className="rounded-2xl p-4 space-y-1.5" style={{background:C.purpleFg,border:`1.5px solid ${C.purple}25`}}>
                <p className="text-xs font-black" style={{color:C.purple}}>📋 YOUR ADDRESS SUMMARY</p>
                <p className="text-sm font-semibold" style={{color:C.text}}>{[form.flat,form.apartment,form.street,form.area].filter(Boolean).join(", ")}</p>
              </div>
            )}
          </div>
        )}
        {!isBiz&&step===3&&(
          <div className="space-y-4">
            <div className="rounded-2xl p-4" style={{background:"#EFF6FF",border:"1.5px solid #BFDBFE"}}>
              <p className="text-sm font-semibold text-blue-700">🔒 Documents are encrypted end-to-end. Used only to verify residency. Never shared publicly.</p>
            </div>
            <div>
              <label className="text-sm font-black mb-2 block" style={{color:C.text}}>Government ID Type</label>
              <div className="grid grid-cols-2 gap-2">
                {ID_TYPES.map(t=>(
                  <button key={t} onClick={()=>setIdType(t)} className="py-2.5 px-3 rounded-xl text-sm font-bold border-2 transition-all"
                    style={idType===t?{borderColor:C.purple,color:C.purple,background:C.purpleFg}:{borderColor:C.border,color:C.muted,background:"#fff"}}>{t}</button>
                ))}
              </div>
            </div>
            <div className="rounded-2xl p-3" style={{background:"#FFF7ED",border:`1px solid ${C.marigold}44`}}>
              <p className="text-xs font-semibold" style={{color:"#92400E"}}>⚠️ Both documents are mandatory to proceed.</p>
            </div>
            {[["id",`Upload ${idType}`,"📄"],["address","Upload Address Proof","🏠"]].map(([k,l,ic])=>(
              <div key={k}>
                <button onClick={()=>{setUploaded(u=>({...u,[k]:true}));setErr(k,null);}} className="w-full py-4 rounded-2xl border-2 border-dashed text-sm font-bold flex items-center justify-center gap-2 transition-all"
                  style={uploaded[k]?{borderColor:C.mint,background:C.mintL,color:C.mint}:errs[k]?{borderColor:C.coral,background:"#FFF1F2",color:C.coral}:{borderColor:C.border,color:C.muted,background:"#fff"}}>
                  {uploaded[k]?"✅ Uploaded!":`${ic} ${l} (Required) →`}
                </button>
                {errs[k]&&<p className="text-xs mt-1 font-semibold" style={{color:C.coral}}>⚠ {errs[k]}</p>}
              </div>
            ))}
          </div>
        )}
        {!isBiz&&step===4&&(
          <div className="space-y-4">
            <p className="text-sm" style={{color:C.muted}}>A live selfie matches your face to your ID. Only verified residents join.</p>
            <button onClick={()=>setUploaded(u=>({...u,selfie:true}))} className="w-full py-20 rounded-3xl border-2 border-dashed flex flex-col items-center justify-center gap-3 transition-all"
              style={uploaded.selfie?{borderColor:C.mint,background:C.mintL}:{borderColor:C.border,background:"#fff"}}>
              {uploaded.selfie?<><span className="text-5xl">✅</span><span className="font-black" style={{color:C.mint}}>Selfie Captured!</span></>:<><span className="text-6xl">🤳</span><span className="text-sm font-bold" style={{color:C.muted}}>Tap to open camera</span></>}
            </button>
            {uploaded.selfie&&(<div className="rounded-2xl p-4" style={{background:"#FFF7EC",border:"1.5px solid #FFB34740"}}><p className="text-sm font-semibold" style={{color:"#b45309"}}>⏳ Under review! SMS confirmation within 24 hours.</p></div>)}
          </div>
        )}

        {/* ══════════════ BUSINESS FLOW ══════════════ */}
        {isBiz&&step===1&&(
          <div className="space-y-4">
            <div className="rounded-2xl p-4" style={{background:"#FFFBF0",border:`1.5px solid ${C.marigold}44`}}>
              <p className="text-sm font-semibold" style={{color:"#92400E"}}>🏪 Set up your business profile. Verified businesses get a badge and can promote posts to local residents.</p>
            </div>
            {[["Business Name","bizName","e.g. CloudKitchen Express","🏪",vBizName,stripAddr],["Owner / Contact Name","ownerName","Your full name","🧑",vName,stripName],["Mobile Number","phone","98450 XXXXX","📱",vPhone,stripPhone]].map(([l,k,p,ic,vfn,sfn])=>(
              <div key={k}>
                <label className="text-sm font-black mb-1.5 block" style={{color:C.text}}>{l}</label>
                <div className="flex items-center rounded-xl px-3 py-2.5 gap-2" style={{background:"#fff",border:`2px solid ${errs[k]?C.coral:C.border}`}}>
                  <span className="text-base">{ic}</span>
                  <input className="flex-1 text-sm font-medium bg-transparent focus:outline-none" style={{color:C.text}}
                    placeholder={p} value={bizForm[k]}
                    onChange={e=>{const v=sfn(e.target.value);setBiz(k,v);if(errs[k])setErr(k,vfn(v));}}
                    onBlur={()=>blur(k,bizForm[k],vfn)}/>
                </div>
                {errs[k]&&<p className="text-xs mt-1 font-semibold" style={{color:C.coral}}>⚠ {errs[k]}</p>}
              </div>
            ))}
            <div>
              <label className="text-sm font-black mb-2 block" style={{color:C.text}}>Business Category</label>
              <div className="grid grid-cols-2 gap-2">
                {BIZ_TYPES.map(t=>(
                  <button key={t} onClick={()=>{setBiz("bizType",t);setErr("bizType",null);}} className="py-2.5 px-3 rounded-xl text-xs font-bold border-2 transition-all text-left"
                    style={bizForm.bizType===t?{borderColor:C.marigold,color:"#92400E",background:C.marigoldL}:{borderColor:C.border,color:C.muted,background:"#fff"}}>{t}</button>
                ))}
              </div>
              {errs.bizType&&<p className="text-xs mt-2 font-semibold" style={{color:C.coral}}>⚠ {errs.bizType}</p>}
            </div>
          </div>
        )}
        {isBiz&&step===2&&(
          <div className="space-y-4">
            <div>
              <SmartInput label="Business Location / Area" placeholder="e.g. Electronic City Phase 1…" groupedOptions={AREA_GROUPS} value={bizForm.area}
                onChange={(v,fromDropdown)=>{setBiz("area",v);fromDropdown?setErr("bizArea",null):setErr("bizArea",vArea(v));}} icon="📍"
                filterFn={stripAddr} error={errs.bizArea}/>
              {errs.bizArea&&<p className="text-xs mt-1 font-semibold" style={{color:C.coral}}>⚠ {errs.bizArea}</p>}
            </div>
            <div>
              <label className="text-sm font-black mb-1.5 block" style={{color:C.text}}>Business Address</label>
              <div className="flex items-center rounded-xl px-3 py-2.5 gap-2" style={{background:"#fff",border:`2px solid ${C.border}`}}>
                <span className="text-base">🏢</span>
                <input className="flex-1 text-sm font-medium bg-transparent focus:outline-none" style={{color:C.text}}
                  placeholder="Shop No., Building, Street…" value={bizForm.address||""}
                  onChange={e=>setBiz("address",stripAddr(e.target.value))}/>
              </div>
            </div>
            {/* Live front photo — mandatory */}
            <div>
              <p className="text-xs font-semibold mb-2" style={{color:"#92400E"}}>📸 Live photo of business front is mandatory</p>
              <button onClick={()=>{setUploaded(u=>({...u,bizFront:true}));setErr("bizFront",null);}}
                className="w-full py-14 rounded-3xl border-2 border-dashed flex flex-col items-center justify-center gap-2 transition-all"
                style={uploaded.bizFront?{borderColor:C.mint,background:C.mintL}:errs.bizFront?{borderColor:C.coral,background:"#FFF1F2"}:{borderColor:C.marigold,background:"#FFFBF0"}}>
                {uploaded.bizFront
                  ?<><span className="text-4xl">✅</span><span className="font-black text-sm" style={{color:C.mint}}>Business Photo Captured!</span></>
                  :<><span className="text-4xl">📸</span><span className="font-bold text-sm" style={{color:"#92400E"}}>Take Live Photo of Business Front</span>
                    <span className="text-xs" style={{color:C.muted}}>Must be taken in real time — no uploads</span></>}
              </button>
              {errs.bizFront&&<p className="text-xs mt-1 font-semibold" style={{color:C.coral}}>⚠ {errs.bizFront}</p>}
            </div>
          </div>
        )}
        {isBiz&&step===3&&(
          <div className="space-y-4">
            <div className="rounded-2xl p-4" style={{background:"#EFF6FF",border:"1.5px solid #BFDBFE"}}>
              <p className="text-sm font-semibold" style={{color:"#1D4ED8"}}>🔒 All documents are encrypted. Used only for verification — never shown publicly.</p>
            </div>
            <div className="rounded-2xl p-3" style={{background:"#FFF7ED",border:`1px solid ${C.marigold}44`}}>
              <p className="text-xs font-semibold" style={{color:"#92400E"}}>⚠️ All documents are mandatory before proceeding.</p>
            </div>
            {/* License or alternative */}
            <div>
              <label className="text-sm font-black mb-2 block" style={{color:C.text}}>Do you have a Business License?</label>
              <div className="flex gap-3">
                {[["yes","✅ Yes, I have one"],["no","❌ No license"]].map(([v,l])=>(
                  <button key={v} onClick={()=>{setHasLicense(v==="yes");setErr("hasLicense",null);}} className="flex-1 py-3 rounded-xl text-sm font-bold border-2 transition-all"
                    style={hasLicense===(v==="yes")?{borderColor:C.purple,color:C.purple,background:C.purpleFg}:errs.hasLicense?{borderColor:C.coral,color:C.coral,background:"#FFF1F2"}:{borderColor:C.border,color:C.muted,background:"#fff"}}>{l}</button>
                ))}
              </div>
              {errs.hasLicense&&<p className="text-xs mt-1 font-semibold" style={{color:C.coral}}>⚠ {errs.hasLicense}</p>}
            </div>
            {hasLicense===true&&(
              <div>
                <button onClick={()=>{setUploaded(u=>({...u,bizLicense:true}));setErr("bizLicense",null);}} className="w-full py-4 rounded-2xl border-2 border-dashed text-sm font-bold flex items-center justify-center gap-2 transition-all"
                  style={uploaded.bizLicense?{borderColor:C.mint,background:C.mintL,color:C.mint}:errs.bizLicense?{borderColor:C.coral,background:"#FFF1F2",color:C.coral}:{borderColor:C.border,color:C.muted,background:"#fff"}}>
                  {uploaded.bizLicense?"✅ License Uploaded!":"📄 Upload Business License (Required) →"}
                </button>
                {errs.bizLicense&&<p className="text-xs mt-1 font-semibold" style={{color:C.coral}}>⚠ {errs.bizLicense}</p>}
              </div>
            )}
            {hasLicense===false&&(
              <div className="space-y-3">
                <div className="rounded-2xl p-3" style={{background:"#FFF7ED",border:"1px solid #FCD34D"}}>
                  <p className="text-xs font-semibold" style={{color:"#78350F"}}>No license? Upload any one of these business-related documents to confirm your business:</p>
                  <p className="text-xs mt-1" style={{color:"#92400E"}}>GST Registration · UDYAM Certificate · Shop & Establishment Registration · Trade License · FSSAI (for food businesses) · Bank account in business name</p>
                </div>
                <div>
                  <button onClick={()=>{setUploaded(u=>({...u,bizDoc:true}));setErr("bizDoc",null);}} className="w-full py-4 rounded-2xl border-2 border-dashed text-sm font-bold flex items-center justify-center gap-2 transition-all"
                    style={uploaded.bizDoc?{borderColor:C.mint,background:C.mintL,color:C.mint}:errs.bizDoc?{borderColor:C.coral,background:"#FFF1F2",color:C.coral}:{borderColor:C.border,color:C.muted,background:"#fff"}}>
                    {uploaded.bizDoc?"✅ Document Uploaded!":"📎 Upload Business Document (Required) →"}
                  </button>
                  {errs.bizDoc&&<p className="text-xs mt-1 font-semibold" style={{color:C.coral}}>⚠ {errs.bizDoc}</p>}
                </div>
              </div>
            )}
            {/* Owner ID — mandatory */}
            <div>
              <button onClick={()=>{setUploaded(u=>({...u,ownerId:true}));setErr("ownerId",null);}} className="w-full py-4 rounded-2xl border-2 border-dashed text-sm font-bold flex items-center justify-center gap-2 transition-all"
                style={uploaded.ownerId?{borderColor:C.mint,background:C.mintL,color:C.mint}:errs.ownerId?{borderColor:C.coral,background:"#FFF1F2",color:C.coral}:{borderColor:C.border,color:C.muted,background:"#fff"}}>
                {uploaded.ownerId?"✅ Owner ID Uploaded!":"🪪 Upload Owner's Government ID (Required) →"}
              </button>
              {errs.ownerId&&<p className="text-xs mt-1 font-semibold" style={{color:C.coral}}>⚠ {errs.ownerId}</p>}
            </div>
          </div>
        )}
        {isBiz&&step===4&&(
          <div className="space-y-4">
            <div className="rounded-2xl p-4" style={{background:"#FFFBF0",border:`1.5px solid ${C.marigold}44`}}>
              <p className="text-sm font-semibold" style={{color:"#92400E"}}>🤳 A live selfie of the business owner holding their ID confirms identity.</p>
            </div>
            <button onClick={()=>setUploaded(u=>({...u,ownerSelfie:true}))} className="w-full py-16 rounded-3xl border-2 border-dashed flex flex-col items-center justify-center gap-3 transition-all"
              style={uploaded.ownerSelfie?{borderColor:C.mint,background:C.mintL}:{borderColor:C.border,background:"#fff"}}>
              {uploaded.ownerSelfie?<><span className="text-5xl">✅</span><span className="font-black" style={{color:C.mint}}>Verification Selfie Done!</span></>:<><span className="text-6xl">🤳</span><span className="text-sm font-bold" style={{color:C.muted}}>Hold your ID and take a selfie</span></>}
            </button>
            {uploaded.ownerSelfie&&(
              <div className="space-y-3">
                <div className="rounded-2xl p-4" style={{background:"#ECFDF5",border:"1px solid #6EE7B7"}}>
                  <p className="text-sm font-black" style={{color:"#065F46"}}>🎉 Almost there! Documents submitted for review.</p>
                  <p className="text-xs mt-1" style={{color:"#047857"}}>Verification within 24–48 hours. Once approved, you can post and promote.</p>
                </div>
                <div className="rounded-2xl p-3" style={{background:C.purpleFg}}>
                  <p className="text-xs font-semibold" style={{color:C.purple}}>💡 After verification, you can promote your business posts to all verified residents of EC Phase 2 and nearby areas!</p>
                </div>
              </div>
            )}
          </div>
        )}

        <div className="mt-8">
          {step<maxStep
            ?<button onClick={handleContinue} className="w-full py-4 rounded-2xl font-black text-lg text-white"
                style={{background:isBiz?`linear-gradient(135deg,${C.marigold},#F59E0B)`:`linear-gradient(135deg,${C.purple},${C.purpleL})`}}>Continue →</button>
            :<button onClick={()=>nav("feed")} className="w-full py-4 rounded-2xl font-black text-lg text-white"
                style={{background:`linear-gradient(135deg,${C.mint},#00967E)`}}>Submit for Verification 🎉</button>
          }
        </div>
      </div>
    </div>
  );
}

// ─── SCREENS: Feed, Events, Map, Messages, Profile ────────────────────────────
// (Same as v2 – keeping them compact here)
const POSTS=[
  // ── MISSING PERSON alert (pinned top – highest urgency) ──
  {id:8,author:"Anand Kumar",apartment:"GM Infinite Smondo",area:"EC Ph 2",av:"AK",avC:"#B91C1C",time:"45m",
   category:"Missing Person",sharedFrom:null,
   missingType:"child",missingName:"Aarav Kumar",missingAge:"7 years",
   missingDesc:"Wearing blue school uniform, white shoes. Last seen near Park Gate C, GM Infinite Smondo.",
   missingLastSeen:"Today 3:30 PM – Park area, EC Phase 2",
   missingContact:"Anand Kumar – 98XX-XXXXX",
   content:"🆘 MISSING CHILD: Aarav Kumar, 7 yrs. Wearing blue school uniform, white shoes. Last seen near Park Gate C, GM Smondo at 3:30 PM today. Please call police 100 or contact Anand Kumar immediately.",
   likes:0,comments:14},
  {id:1,author:"Priya Venkat",apartment:"Prestige Sunrise Park",area:"EC Ph 1",av:"PV",avC:"#7B4BB8",time:"2h",category:"Safety",content:"🛡️ Alert: Suspicious persons near Gate 2 last night ~10 PM. Security notified. Please lock up and call 100 if you see anything unusual.",likes:47,comments:12,sharedFrom:null},
  {id:2,author:"Ramesh Babu",apartment:"Shriram Signia",area:"EC Ph 1",av:"RB",avC:"#FFB347",time:"4h",category:"Lost & Found",content:"🐕 Found a golden retriever near Infosys Signal – blue collar, no name tag. DM if yours. Safe with me.",likes:89,comments:31,sharedFrom:null},
  {id:3,author:"Deepa Krishnan",apartment:"Mahaveer Ranches",area:"EC Ph 2",av:"DK",avC:"#00B89F",time:"6h",category:"Recommendation",content:"⭐ Sri Lakshmi Vegetables near Hebbagodi bus stop – freshest produce! Ask for Kumar. Open 6 AM–9 PM.",likes:134,comments:44,sharedFrom:null},
  // Cross-shared posts from nearby communities (admin can remove these)
  {id:6,author:"Kavya Sharma",apartment:"Adarsh Welkin Park",area:"Hebbagodi",av:"KS",avC:"#FF6B7A",time:"3h",category:"Safety",content:"🚨 Warning: Chain snatching incident near Hebbagodi bus terminal around 7 PM today. Avoid that stretch after dark. Shared for awareness.",likes:31,comments:8,sharedFrom:"Hebbagodi"},
  {id:7,author:"Suresh P.",apartment:"Ozone Urbana",area:"Bommasandra",av:"SP",avC:"#FFB347",time:"5h",category:"Lost & Found",content:"🔍 Lost: Brown leather wallet near Bommasandra industrial area yesterday afternoon. Contains Aadhar & ATM card. Please contact if found – reward.",likes:14,comments:5,sharedFrom:"Bommasandra"},
  {id:4,author:"Arjun Nair",apartment:"Godrej E-City",area:"EC Ph 1",av:"AN",avC:"#FF6B7A",time:"8h",category:"Services",content:"🔧 Reliable plumber – Suresh (9845-XXXXX). Fixed pipeline in under 2 hrs for ₹500. Adding to community directory!",likes:62,comments:18,sharedFrom:null},
  {id:5,author:"Meena S.",apartment:"Celebrity Paradise",area:"Neeladri Nagar",av:"MS",avC:"#6B7FF0",time:"1d",category:"General",content:"💡 BESCOM power cut tomorrow 9 AM–2 PM across Neeladri Nagar. Charge your devices tonight!",likes:201,comments:67,sharedFrom:null},
];

// ─── Business & Promotion Data ────────────────────────────────────────────────
const PROMO_TIERS=[
  {tier:500,label:"Premium Sidebar",desc:"Featured in sidebar of every feed view. Maximum visibility.",badge:"⭐ FEATURED",color:"#F59E0B",colorL:"#FFFBEB",icon:"🏆",perks:["Sidebar placement","Top of feed","Bold border","All-day display"]},
  {tier:250,label:"Priority Feed",desc:"Pinned at the top of the regular feed, above ₹100 promotions.",badge:"🔼 PRIORITY",color:"#8B5CF6",colorL:"#F5F3FF",icon:"🥈",perks:["Top of main feed","Priority over ₹100","Bold highlight","All-day display"]},
  {tier:100,label:"Boosted Post",desc:"Boosted above regular posts in the feed. Cost-effective reach.",badge:"📢 BOOSTED",color:C.mint,colorL:C.mintL,icon:"🥉",perks:["Above regular posts","Boosted label","All-day display"]},
];
const BIZ_POSTS=[
  {id:101,bizName:"CloudKitchen Express",bizType:"Restaurant / Food",owner:"Ravi Kumar",av:"CK",avC:"#EF4444",area:"EC Phase 2",
   content:"🍱 Freshly cooked North & South Indian meals — tiffin subscriptions starting ₹99/day! Free delivery within EC Phase 2. Order by 9 AM for lunch.",
   promoTier:500,promoTime:1,contact:"Order via WhatsApp: 98XX-XXXXX",verified:true},
  {id:102,bizName:"QuickFix Electricals",bizType:"Services / Repairs",owner:"Suresh T.",av:"QF",avC:"#3B82F6",area:"EC Phase 1 & 2",
   content:"⚡ Licensed electrician — wiring, MCB, inverter installation, fan & AC repairs. Same-day service. All EC areas. 10% off for MyTown360 members!",
   promoTier:250,promoTime:2,contact:"Call: 97XX-XXXXX",verified:true},
  {id:103,bizName:"FreshMart Organics",bizType:"Grocery / Supermart",owner:"Priya S.",av:"FM",avC:"#10B981",area:"Neeladri Nagar",
   content:"🥦 100% organic vegetables & fruits — sourced directly from farms. Daily delivery 7 AM–9 AM. First order 20% off with code MYTOWN20.",
   promoTier:100,promoTime:3,contact:"Order: 96XX-XXXXX",verified:true},
  {id:104,bizName:"Glow Beauty Studio",bizType:"Beauty / Wellness",owner:"Anita R.",av:"GB",avC:"#EC4899",area:"EC Phase 1",
   content:"💅 Hair, skin & bridal packages at unbeatable prices. Women's only. Book appointments in advance. Mention MyTown360 for 15% off!",
   promoTier:100,promoTime:4,contact:"Book: 95XX-XXXXX",verified:true},
];

const EVENTS=[
  {id:1,title:"Community Yoga Camp",date:"Mar 8",time:"6:30 AM",location:"Prestige Sunrise Park Clubhouse",category:"Wellness",attendees:43,icon:"🧘",col:"#00B89F"},
  {id:2,title:"Holi Celebrations 2026",date:"Mar 14",time:"10:00 AM",location:"GM Infinite Smondo Park",category:"Festival",attendees:312,icon:"🎨",col:"#FF6B7A"},
  {id:3,title:"Women's Safety Drive",date:"Mar 18",time:"5:00 PM",location:"EC Community Hall Ph 1",category:"Safety",attendees:78,icon:"🛡️",col:"#5C2D91"},
  {id:4,title:"Kids Coding Workshop",date:"Mar 22",time:"10:00 AM",location:"Kolte Patil iTowers",category:"Education",attendees:25,icon:"💻",col:"#6B7FF0"},
];
const LISTINGS=[
  {id:1,type:"For Sale",title:"Philips Air Fryer 2L",price:"₹2,800",seller:"Kavitha R.",area:"EC Ph 2",icon:"🍳",age:"2h",col:"#FFB347"},
  {id:2,type:"Free",title:"Baby clothes 0–6 months",price:"FREE",seller:"Sunitha P.",area:"Hebbagodi",icon:"👶",age:"5h",col:"#00B89F"},
  {id:3,type:"For Rent",title:"2BHK Shriram Signia (Furn)",price:"₹28k/mo",seller:"Venkat K.",area:"EC Ph 1",icon:"🏠",age:"1d",col:"#5C2D91"},
  {id:4,type:"Service",title:"Home Deep Clean 3BHK",price:"₹1,200",seller:"CleanPro EC",area:"All areas",icon:"🧹",age:"2d",col:"#6B7FF0"},
];
const MSGS=[
  {id:1,name:"Ramesh Babu",av:"RB",avC:"#FFB347",preview:"Is the dog still with you?",time:"10:23 AM",unread:2},
  {id:2,name:"MyTown 360 Admin",av:"MT",avC:C.purple,preview:"Your address verification is complete!",time:"9:45 AM",unread:1},
  {id:3,name:"Kavitha R.",av:"KR",avC:"#6B7FF0",preview:"Still interested in the Air Fryer?",time:"Yesterday",unread:0},
];
const AREAS_LIST=[
  {name:"Electronic City Phase 1",pin:"560100"},{name:"Electronic City Phase 2",pin:"560100"},
  {name:"Neeladri Nagar",pin:"560100"},{name:"Doddathogur",pin:"560100"},
  {name:"Hebbagodi",pin:"560099"},{name:"Bommasandra",pin:"560099"},
  {name:"Veerasandra",pin:"560100"},{name:"Huskur Road Area",pin:"560100"},
  {name:"Chandapura",pin:"562106"},{name:"Kudlu",pin:"560068"},
];
// ─── Nearby Localities (within ~10 km of EC) ─────────────────────────────────────
const NEARBY_LOCALITIES = [
  { name:"Begur",            dist:"~3 km",  dir:"N",  note:"Historic fort & lake. Weekend outing spot.",       color:"#7C3AED" },
  { name:"Haralur",          dist:"~4 km",  dir:"NE", note:"Popular residential area for EC professionals.",   color:"#0891B2" },
  { name:"Doddakannelli",    dist:"~4 km",  dir:"NE", note:"Growing layout near Sarjapura Road.",              color:"#059669" },
  { name:"Kasavanahalli",    dist:"~5 km",  dir:"NE", note:"Residential & commercial corridor near ORR.",      color:"#D97706" },
  { name:"Dommasandra",      dist:"~5 km",  dir:"E",  note:"Adjacent to EC boundary. Village-to-urban layout.",color:"#DC2626" },
  { name:"Panathur",         dist:"~5 km",  dir:"NE", note:"Near ORR–Sarjapura junction. Good connectivity.",  color:"#2563EB" },
  { name:"Gunjur",           dist:"~6 km",  dir:"NE", note:"Expanding residential zone on Sarjapura Road.",    color:"#059669" },
  { name:"Bellandur",        dist:"~6 km",  dir:"N",  note:"Tech corridor on ORR. Many IT offices & malls.",   color:"#7C3AED" },
  { name:"HSR Layout",       dist:"~7 km",  dir:"NW", note:"Popular residential hub. Good schools & eateries.",color:"#EA580C" },
  { name:"Sarjapura",        dist:"~8 km",  dir:"E",  note:"Major nearby township. Schools, hospitals, malls.",color:"#0891B2" },
  { name:"Varthur",          dist:"~10 km", dir:"NE", note:"Near Whitefield corridor. Growing residential.",   color:"#6B7280" },
  { name:"Chandapura",       dist:"~5 km",  dir:"SE", note:"KSRTC connectivity, Bommasandra adjacent.",        color:"#B45309" },
];

const DIRECTORY=[["🍽️","Restaurants & Cafés","8"],["🛒","Grocery & Supermarkets","10"],["🔧","Service Providers","41"],["🏥","Hospitals & Clinics","7"],["🚌","Transport & Autos","9"],["🏫","Schools & Daycare","13"],["🌳","Parks & Recreation","9"],["⛽","Petrol Pumps","5"],["🏨","Hotels & Stay","5"],["🛕","Temples & Worship","9"],["🎬","Cinemas","3"],["🏧","ATMs","8"]];

// ─── Police Alert Gate (shown before Missing Person form) ────────────────────
function PoliceAlertModal({onOk}){
  return(
    <div style={{position:"fixed",inset:0,zIndex:300,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(26,16,51,0.72)",backdropFilter:"blur(6px)",padding:"0 16px"}}>
      <div style={{width:"100%",maxWidth:370,background:"#fff",borderRadius:24,overflow:"hidden",boxShadow:"0 24px 60px rgba(185,28,28,0.3)"}}>
        {/* Red header */}
        <div style={{background:C.crimson,padding:"20px 24px",textAlign:"center"}}>
          <div style={{fontSize:40,marginBottom:6}}>🚨</div>
          <div style={{fontWeight:900,fontSize:18,color:"#fff"}}>MISSING PERSON?</div>
          <div style={{fontSize:12,color:"rgba(255,255,255,0.85)",marginTop:2}}>Please contact the police immediately</div>
        </div>
        <div style={{padding:"18px 20px",display:"flex",flexDirection:"column",gap:10}}>
          {/* Emergency numbers */}
          <div style={{display:"flex",flexDirection:"column",gap:8}}>
            {[
              {icon:"🚔",label:"Police",num:"100",col:"#1D4ED8",colL:"#EFF6FF"},
              {icon:"👶",label:"Childline (Missing Children)",num:"1098",col:"#7C3AED",colL:"#F5F3FF"},
              {icon:"🆘",label:"Emergency Services",num:"112",col:C.crimson,colL:C.crimsonL},
            ].map(({icon,label,num,col,colL})=>(
              <div key={num} style={{display:"flex",alignItems:"center",gap:12,padding:"10px 14px",borderRadius:12,background:colL,border:`1px solid ${col}22`}}>
                <span style={{fontSize:20,width:26,textAlign:"center"}}>{icon}</span>
                <div style={{flex:1}}>
                  <div style={{fontSize:11,color:"#6B7280",fontWeight:600}}>{label}</div>
                  <div style={{fontSize:16,fontWeight:900,color:col,letterSpacing:1}}>{num}</div>
                </div>
                <div style={{fontSize:10,fontWeight:700,padding:"3px 8px",borderRadius:99,background:col,color:"#fff"}}>CALL NOW</div>
              </div>
            ))}
          </div>
          <div style={{padding:"10px 12px",borderRadius:10,background:"#FFFBEB",border:"1px solid #FCD34D",fontSize:11,color:"#78350F",lineHeight:1.5}}>
            ⚠️ Posting on MyTown 360 does <span style={{fontWeight:700}}>not</span> replace an official police report. Always file a First Information Report (FIR) first.
          </div>
          <button onClick={onOk}
            style={{width:"100%",padding:"13px",borderRadius:14,background:C.crimson,color:"#fff",fontWeight:900,fontSize:14,border:"none",cursor:"pointer",marginTop:2}}>
            I have noted this — Continue Posting
          </button>
        </div>
      </div>
    </div>
  );
}

// ─── Image Upload (for posts/listings) ───────────────────────────────────────
function ImageUpload({images, onChange, maxImages=4, label="Add Photos"}){
  const handleClick=()=>{
    // Simulate selecting up to 2 demo images
    if(images.length<maxImages){
      onChange([...images,{id:Date.now(),name:`photo_${images.length+1}.jpg`}]);
    }
  };
  const remove=(id)=>onChange(images.filter(x=>x.id!==id));
  return(
    <div>
      <div style={{fontSize:12,fontWeight:700,color:C.text,marginBottom:6}}>📷 {label} <span style={{color:C.muted,fontWeight:500}}>(up to {maxImages})</span></div>
      <div style={{display:"flex",gap:8,flexWrap:"wrap"}}>
        {images.map(img=>(
          <div key={img.id} style={{position:"relative",width:68,height:68,borderRadius:12,background:C.purpleFg,border:`1.5px solid ${C.border}`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:26}}>
            🖼️
            <button onClick={()=>remove(img.id)}
              style={{position:"absolute",top:-6,right:-6,width:18,height:18,borderRadius:99,background:C.coral,color:"#fff",fontWeight:900,fontSize:10,border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",lineHeight:1}}>✕</button>
          </div>
        ))}
        {images.length<maxImages&&(
          <button onClick={handleClick}
            style={{width:68,height:68,borderRadius:12,border:`2px dashed ${C.border}`,background:"#fff",cursor:"pointer",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:2}}>
            <span style={{fontSize:22}}>📷</span>
            <span style={{fontSize:9,color:C.muted,fontWeight:600}}>Add</span>
          </button>
        )}
      </div>
      {images.length>0&&<div style={{fontSize:10,color:C.muted,marginTop:4}}>{images.length} photo{images.length>1?"s":""} added</div>}
    </div>
  );
}

// ─── Dispatch Modal (shown after posting an alert category) ──────────────────
function DispatchModal({category, memberCount, onDone}){
  const isMissing=category==="Missing Person";
  const isLF=category==="Lost & Found";
  const col=isMissing?C.crimson:isLF?C.marigold:C.coral;
  const colL=isMissing?C.crimsonL:isLF?C.marigoldL:C.coralL;
  const channels=[
    {icon:"📱",label:"App Push Notification",detail:`${memberCount} verified members in EC Phase 2`,done:true},
    {icon:"📧",label:"Email Alert",detail:`${memberCount} registered email addresses`,done:true},
    {icon:"💬",label:"SMS Alert",detail:`${memberCount} registered mobile numbers`,done:true},
    ...(isMissing?[{icon:"🔊",label:"Urgent Tone Alert",detail:"Special alarm tone played on all active devices in area",done:true,urgent:true}]:[]),
  ];
  return(
    <div style={{position:"fixed",inset:0,zIndex:200,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(26,16,51,0.65)",backdropFilter:"blur(6px)",padding:"0 16px"}}>
      <div style={{width:"100%",maxWidth:380,background:"#fff",borderRadius:24,overflow:"hidden",boxShadow:"0 20px 60px rgba(0,0,0,0.25)"}}>
        {/* Header */}
        <div style={{background:col,padding:"18px 20px",textAlign:"center"}}>
          <div style={{fontSize:32,marginBottom:4}}>{isMissing?"🚨":isLF?"🔍":"🛡️"}</div>
          <div style={{fontWeight:900,fontSize:16,color:"#fff"}}>{isMissing?"MISSING PERSON ALERT":"COMMUNITY ALERT"} DISPATCHED</div>
          <div style={{fontSize:12,color:"rgba(255,255,255,0.85)",marginTop:2}}>Notification sent to your area</div>
        </div>
        {/* Member count badge */}
        <div style={{padding:"14px 20px 10px",display:"flex",justifyContent:"center"}}>
          <div style={{display:"inline-flex",alignItems:"center",gap:8,padding:"8px 16px",borderRadius:99,background:colL,border:`1.5px solid ${col}33`}}>
            <span style={{fontSize:18}}>👥</span>
            <div>
              <div style={{fontSize:14,fontWeight:900,color:col}}>{memberCount} Members Notified</div>
              <div style={{fontSize:10,color:C.muted}}>Verified residents of EC Phase 2</div>
            </div>
          </div>
        </div>
        {/* Channel breakdown */}
        <div style={{padding:"4px 20px 14px",display:"flex",flexDirection:"column",gap:8}}>
          {channels.map((ch,i)=>(
            <div key={i} style={{display:"flex",alignItems:"center",gap:10,padding:"10px 12px",borderRadius:12,background:ch.urgent?C.crimsonL:C.surface,border:`1px solid ${ch.urgent?C.crimson+"33":C.border}`}}>
              <span style={{fontSize:20,width:28,textAlign:"center"}}>{ch.icon}</span>
              <div style={{flex:1}}>
                <div style={{fontSize:13,fontWeight:700,color:ch.urgent?C.crimson:C.text}}>{ch.label}</div>
                <div style={{fontSize:10,color:C.muted,marginTop:1}}>{ch.detail}</div>
              </div>
              <div style={{width:20,height:20,borderRadius:99,background:ch.urgent?"#B91C1C":"#22C55E",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0}}>
                <span style={{color:"#fff",fontSize:11,fontWeight:900}}>✓</span>
              </div>
            </div>
          ))}
        </div>
        {/* Special tone note */}
        {isMissing&&(
          <div style={{margin:"0 20px 12px",padding:"10px 14px",borderRadius:12,background:"#FFF7ED",border:"1px solid #F97316",display:"flex",gap:8,alignItems:"flex-start"}}>
            <span style={{fontSize:16,flexShrink:0}}>ℹ️</span>
            <div style={{fontSize:11,color:"#7C3510",lineHeight:1.5}}>
              <span style={{fontWeight:700}}>Special alert tone</span> is a unique high-priority sound played on all MyTown360 apps even when the phone is on silent, to ensure maximum visibility for missing person cases.
            </div>
          </div>
        )}
        <div style={{padding:"0 20px 20px"}}>
          <button onClick={onDone}
            style={{width:"100%",padding:"13px",borderRadius:14,background:col,color:"#fff",fontWeight:900,fontSize:14,border:"none",cursor:"pointer"}}>
            {isMissing?"Share with nearby areas too →":"Got it"}
          </button>
        </div>
      </div>
    </div>
  );
}

// ─── Notification Toast ───────────────────────────────────────────────────────
function NotificationToast({alerts, onDismiss}){
  if(!alerts.length) return null;
  return(
    <div style={{position:"fixed",top:70,left:"50%",transform:"translateX(-50%)",width:"calc(100% - 24px)",maxWidth:406,zIndex:90,display:"flex",flexDirection:"column",gap:6}}>
      {alerts.map(a=>{
        const isMissing=a.cat==="Missing Person";
        const isLF=a.cat==="Lost & Found";
        const col=isMissing?C.crimson:isLF?C.marigold:C.coral;
        const colL=isMissing?C.crimsonL:isLF?C.marigoldL:C.coralL;
        const toastIcon=isMissing?"🚨":isLF?"🔍":"⚠️";
        const label=isMissing?"MISSING PERSON ALERT":isLF?"LOST & FOUND":"SAFETY ALERT";
        return(
          <div key={a.id} style={{borderRadius:14,overflow:"hidden",boxShadow:`0 6px 28px ${col}44`}}>
            {/* Coloured header */}
            <div style={{background:col,padding:"8px 14px",display:"flex",alignItems:"center",justifyContent:"space-between"}}>
              <div style={{display:"flex",alignItems:"center",gap:8}}>
                <span style={{fontSize:16}}>{toastIcon}</span>
                <span style={{color:"#fff",fontWeight:900,fontSize:12}}>{label} · {a.area}</span>
                {isMissing&&<span style={{fontSize:9,fontWeight:800,padding:"2px 6px",borderRadius:99,background:"rgba(255,255,255,0.25)",color:"#fff"}}>🔊 URGENT TONE</span>}
              </div>
              <button onClick={()=>onDismiss(a.id)} style={{color:"#fff",fontWeight:900,fontSize:14,background:"none",border:"none",cursor:"pointer",padding:"0 4px"}}>✕</button>
            </div>
            {/* Content */}
            <div style={{background:"#fff",padding:"10px 14px",display:"flex",gap:10,alignItems:"flex-start"}}>
              <div style={{width:28,height:28,borderRadius:99,background:colL,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,fontSize:13}}>
                {isMissing?"👶":isLF?"🐾":"⚠️"}
              </div>
              <div style={{flex:1}}>
                <div style={{fontSize:12,fontWeight:700,color:C.text,lineHeight:1.4}}>{a.content}</div>
                <div style={{fontSize:10,color:C.muted,marginTop:2}}>Posted by <span style={{fontWeight:600}}>{a.author}</span> · Just now</div>
                {/* Dispatch channel badges */}
                <div style={{marginTop:6,display:"flex",flexWrap:"wrap",gap:4}}>
                  <span style={{fontSize:9,fontWeight:800,padding:"2px 7px",borderRadius:99,background:colL,color:col,border:`1px solid ${col}44`}}>🔔 {a.memberCount} push</span>
                  <span style={{fontSize:9,fontWeight:800,padding:"2px 7px",borderRadius:99,background:"#F0FDF4",color:"#15803D",border:"1px solid #86EFAC"}}>📧 email sent</span>
                  <span style={{fontSize:9,fontWeight:800,padding:"2px 7px",borderRadius:99,background:"#EFF6FF",color:"#1D4ED8",border:"1px solid #BFDBFE"}}>💬 SMS sent</span>
                  {isMissing&&<span style={{fontSize:9,fontWeight:800,padding:"2px 7px",borderRadius:99,background:C.crimsonL,color:C.crimson,border:`1px solid ${C.crimson}44`}}>🔊 urgent tone</span>}
                  {a.sharedAreas&&a.sharedAreas.length>0&&(
                    <span style={{fontSize:9,fontWeight:700,padding:"2px 7px",borderRadius:99,background:C.purpleFg,color:C.purple}}>📡 {a.sharedAreas.length} areas</span>
                  )}
                </div>
              </div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ─── Cross-Share Modal ────────────────────────────────────────────────────────
function CrossShareModal({category, onShare, onSkip}){
  const [sel,setSel]=useState([]);
  const toggle=(a)=>setSel(s=>s.includes(a)?s.filter(x=>x!==a):[...s,a]);
  return(
    <div style={{position:"fixed",inset:0,zIndex:150,display:"flex",alignItems:"flex-end",justifyContent:"center",background:"rgba(26,16,51,0.55)",backdropFilter:"blur(4px)"}}>
      <div style={{width:"100%",maxWidth:430,background:"#fff",borderRadius:"24px 24px 0 0",padding:"0 0 32px"}}>
        <div style={{display:"flex",justifyContent:"center",paddingTop:12}}><div style={{width:40,height:4,borderRadius:99,background:C.border}}/></div>
        <div style={{padding:"14px 20px 10px"}}>
          <div style={{fontWeight:900,fontSize:16,color:C.text}}>Share with Nearby Communities?</div>
          <div style={{fontSize:12,color:C.muted,marginTop:4,lineHeight:1.5}}>
            Your <span style={{fontWeight:700,color:category==="Safety"?C.coral:C.marigold}}>{category}</span> post has been sent to your area.
            Nearby communities may benefit from this information too.
          </div>
          <div style={{marginTop:4,padding:"8px 10px",borderRadius:10,background:category==="Safety"?C.coralL:C.marigoldL,fontSize:11,color:C.muted}}>
            ℹ️ Community admins of selected areas can remove your post if they consider it off-topic or spam.
          </div>
        </div>
        <div style={{padding:"0 20px",display:"grid",gridTemplateColumns:"1fr 1fr",gap:8,maxHeight:200,overflowY:"auto"}}>
          {NEARBY_AREAS.map(area=>{
            const on=sel.includes(area);
            return(
              <button key={area} onClick={()=>toggle(area)}
                style={{display:"flex",alignItems:"center",gap:8,padding:"10px 12px",borderRadius:12,border:`1.5px solid ${on?C.purple:C.border}`,background:on?C.purpleFg:"#fff",cursor:"pointer",textAlign:"left"}}>
                <div style={{width:18,height:18,borderRadius:99,border:`2px solid ${on?C.purple:C.border}`,background:on?C.purple:"#fff",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0}}>
                  {on&&<span style={{color:"#fff",fontSize:10,fontWeight:900}}>✓</span>}
                </div>
                <span style={{fontSize:12,fontWeight:600,color:on?C.purple:C.text,lineHeight:1.3}}>{area}</span>
              </button>
            );
          })}
        </div>
        <div style={{padding:"14px 20px 0",display:"flex",flexDirection:"column",gap:8}}>
          <button onClick={()=>onShare(sel)}
            style={{width:"100%",padding:"12px",borderRadius:14,background:sel.length>0?C.purple:C.border,color:sel.length>0?"#fff":C.muted,fontWeight:900,fontSize:14,border:"none",cursor:"pointer"}}>
            {sel.length>0?`📡 Share to ${sel.length} Nearby Area${sel.length>1?"s":""}`:"Select areas above"}
          </button>
          <button onClick={onSkip}
            style={{width:"100%",padding:"11px",borderRadius:14,background:C.surface,color:C.muted,fontWeight:700,fontSize:13,border:`1.5px solid ${C.border}`,cursor:"pointer"}}>
            Skip — My Area Only
          </button>
        </div>
      </div>
    </div>
  );
}

// ─── Reaction Bar ─────────────────────────────────────────────────────────────
function ReactionBar({postId, baseCounts, myReaction, onReact}){
  const [open,setOpen]=useState(false);
  const counts={...baseCounts};
  if(myReaction) counts[myReaction]=(counts[myReaction]||0)+1;
  const top=Object.entries(counts).filter(([,v])=>v>0).sort((a,b)=>b[1]-a[1]).slice(0,3);
  const total=Object.values(counts).reduce((s,v)=>s+v,0);
  return(
    <div>
      {/* Reaction summary row */}
      {total>0&&(
        <div style={{display:"flex",alignItems:"center",gap:6,padding:"4px 16px",borderBottom:`1px solid ${C.border}`}}>
          <div style={{display:"flex",gap:2}}>
            {top.map(([id])=>{const r=REACTIONS.find(x=>x.id===id);return r?<span key={id} style={{fontSize:14}}>{r.emoji}</span>:null;})}
          </div>
          <span style={{fontSize:11,color:C.muted}}>{total} reaction{total!==1?"s":""}</span>
        </div>
      )}
      {/* Picker popup */}
      {open&&(
        <div style={{padding:"8px 12px",background:C.surface,borderBottom:`1px solid ${C.border}`,display:"flex",gap:4,flexWrap:"wrap"}}>
          {REACTIONS.map(r=>{
            const chosen=myReaction===r.id;
            return(
              <button key={r.id} onClick={()=>{onReact(postId,chosen?null:r.id);setOpen(false);}}
                title={r.label}
                style={{display:"flex",flexDirection:"column",alignItems:"center",gap:1,padding:"5px 7px",borderRadius:10,border:`1.5px solid ${chosen?C.purple:C.border}`,background:chosen?C.purpleFg:"#fff",cursor:"pointer",minWidth:38}}>
                <span style={{fontSize:20,lineHeight:1}}>{r.emoji}</span>
                <span style={{fontSize:8,color:chosen?C.purple:C.muted,fontWeight:600}}>{r.label}</span>
              </button>
            );
          })}
        </div>
      )}
      {/* Action bar */}
      <div style={{padding:"10px 16px",display:"flex",gap:16,alignItems:"center"}}>
        <button onClick={()=>setOpen(o=>!o)}
          style={{display:"flex",alignItems:"center",gap:5,fontSize:13,fontWeight:700,color:myReaction?C.purple:C.muted,background:"none",border:"none",cursor:"pointer"}}>
          <span style={{fontSize:16}}>{myReaction?REACTIONS.find(r=>r.id===myReaction)?.emoji:"🤍"}</span>
          <span>{myReaction?REACTIONS.find(r=>r.id===myReaction)?.label:"React"}</span>
        </button>
        <button style={{display:"flex",alignItems:"center",gap:5,fontSize:13,fontWeight:600,color:C.muted,background:"none",border:"none",cursor:"pointer"}}>💬 Comment</button>
        <button style={{display:"flex",alignItems:"center",gap:5,fontSize:13,fontWeight:600,color:C.muted,background:"none",border:"none",cursor:"pointer"}}>↗️ Share</button>
      </div>
    </div>
  );
}

// ─── Post Composer (Category-First) ──────────────────────────────────────────
function PostComposer({onPost}){
  const [step,setStep]=useState(0); // 0=closed 1=pick-category 2=write
  const [cat,setCat]=useState("");
  const [draft,setDraft]=useState("");
  const [urgency,setUrgency]=useState("high");
  const [lostType,setLostType]=useState("lost");
  const [blocked,setBlocked]=useState(false);
  const [images,setImages]=useState([]);
  const [policeAlert,setPoliceAlert]=useState(false); // show police gate modal
  // Missing Person specific fields
  const [missingType,setMissingType]=useState("child");
  const [missingName,setMissingName]=useState("");
  const [missingAge,setMissingAge]=useState("");
  const [missingLastSeen,setMissingLastSeen]=useState("");
  const [missingContact,setMissingContact]=useState("");
  const meta=CAT_META[cat]||{};
  const isAlert=ALERT_CATEGORIES.includes(cat);
  const isMissing=cat==="Missing Person";
  const isLF=cat==="Lost & Found";

  const handleDraft=(v)=>{ setDraft(v); setBlocked(checkViolation(v)); };
  const resetAll=()=>{setStep(0);setCat("");setDraft("");setBlocked(false);setImages([]);setMissingName("");setMissingAge("");setMissingLastSeen("");setMissingContact("");setPoliceAlert(false);};

  const missingReady=isMissing&&missingName.trim()&&missingLastSeen.trim();
  const canPost=isMissing?missingReady:(draft.trim()&&!blocked);

  const doPost=()=>{
    if(!canPost) return;
    let content=draft;
    let extra={};
    if(isMissing){
      content=`🆘 MISSING ${missingType==="child"?"CHILD":"PERSON"}: ${missingName}${missingAge?`, ${missingAge}`:""}. Last seen: ${missingLastSeen}.${draft.trim()?" "+draft.trim():""}${missingContact?" Contact: "+missingContact:""}`;
      extra={missingType,missingName,missingAge,missingLastSeen,missingContact};
    }
    onPost({category:cat,content,urgency:cat==="Safety"?urgency:null,lostType:cat==="Lost & Found"?lostType:null,images,...extra});
    resetAll();
  };

  if(step===0) return(
    <div style={{display:"flex",alignItems:"center",gap:12,padding:"14px 16px",background:"#fff",borderRadius:16,border:`1.5px solid ${C.border}`}}>
      <div style={{width:36,height:36,borderRadius:10,background:C.purple,display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:900,fontSize:12,flexShrink:0}}>MT</div>
      <button onClick={()=>setStep(1)} style={{flex:1,textAlign:"left",fontSize:13,color:C.muted,background:C.surface,borderRadius:10,padding:"9px 14px",border:`1px solid ${C.border}`,cursor:"pointer",fontWeight:500}}>
        Share with your neighbourhood…
      </button>
    </div>
  );

  if(step===1) return(
    <div style={{background:"#fff",borderRadius:16,border:`1.5px solid ${C.border}`,overflow:"hidden"}}>
      <div style={{padding:"12px 16px",borderBottom:`1.5px solid ${C.border}`,display:"flex",alignItems:"center",justifyContent:"space-between"}}>
        <div style={{fontWeight:900,fontSize:14,color:C.text}}>What are you posting about?</div>
        <button onClick={()=>setStep(0)} style={{width:28,height:28,borderRadius:8,background:C.surface,border:`1px solid ${C.border}`,cursor:"pointer",fontWeight:900,color:C.muted,fontSize:14}}>✕</button>
      </div>
      {/* Police Alert Gate Modal */}
      {policeAlert&&<PoliceAlertModal onOk={()=>{setPoliceAlert(false);setStep(2);}}/>}
      <div style={{padding:"10px 12px",display:"flex",flexDirection:"column",gap:8}}>
        {/* Missing Person – full-width, visually distinct urgent button */}
        <button onClick={()=>{setCat("Missing Person");setPoliceAlert(true);}}
          style={{display:"flex",alignItems:"center",gap:12,padding:"14px 16px",borderRadius:14,border:`2px solid ${C.crimson}`,background:C.crimsonL,cursor:"pointer",textAlign:"left",width:"100%"}}>
          <div style={{width:40,height:40,borderRadius:12,background:C.crimson,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0}}>
            <span style={{fontSize:22}}>🆘</span>
          </div>
          <div style={{flex:1}}>
            <div style={{display:"flex",alignItems:"center",gap:6}}>
              <span style={{fontSize:14,fontWeight:900,color:C.crimson}}>Missing Person / Child</span>
              <span style={{fontSize:9,fontWeight:800,padding:"2px 7px",borderRadius:99,background:C.crimson,color:"#fff"}}>🔊 URGENT TONE</span>
            </div>
            <div style={{fontSize:11,color:"#7F1D1D",marginTop:1}}>Email + SMS + special alarm sent to all members</div>
          </div>
        </button>
        {/* Other categories – 2-column grid */}
        <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8}}>
          {Object.entries(CAT_META).filter(([n])=>n!=="Missing Person").map(([name,m])=>(
            <button key={name} onClick={()=>{setCat(name);setStep(2);}}
              style={{display:"flex",alignItems:"center",gap:10,padding:"12px 14px",borderRadius:14,border:`2px solid ${m.color}22`,background:`${m.color}0D`,cursor:"pointer",textAlign:"left"}}>
              <span style={{fontSize:22,width:28,textAlign:"center"}}>{m.icon}</span>
              <div>
                <div style={{fontSize:13,fontWeight:700,color:C.text}}>{name}</div>
                {ALERT_CATEGORIES.includes(name)&&name!=="Missing Person"&&<div style={{fontSize:9,fontWeight:800,color:m.color}}>🔔 INSTANT ALERT</div>}
              </div>
            </button>
          ))}
        </div>
      </div>
    </div>
  );

  return(
    <div style={{background:"#fff",borderRadius:16,border:`1.5px solid ${isMissing?C.crimson:C.border}`,overflow:"hidden"}}>
      {/* Category header stripe */}
      <div style={{background:meta.color||C.purple,padding:"10px 16px",display:"flex",alignItems:"center",justifyContent:"space-between"}}>
        <div style={{display:"flex",alignItems:"center",gap:8}}>
          <span style={{fontSize:18}}>{meta.icon}</span>
          <span style={{fontWeight:900,color:"#fff",fontSize:14}}>{cat}</span>
          {isMissing&&<span style={{fontSize:10,fontWeight:800,padding:"2px 8px",borderRadius:99,background:"rgba(255,255,255,0.22)",color:"#fff"}}>🔊 URGENT TONE ALERT</span>}
          {isAlert&&!isMissing&&<span style={{fontSize:10,fontWeight:800,padding:"2px 8px",borderRadius:99,background:"rgba(255,255,255,0.22)",color:"#fff"}}>🔔 INSTANT ALERT</span>}
        </div>
        <button onClick={()=>setStep(1)} style={{fontSize:11,color:"rgba(255,255,255,0.8)",background:"rgba(255,255,255,0.18)",borderRadius:8,border:"none",padding:"4px 8px",cursor:"pointer",fontWeight:700}}>← Change</button>
      </div>
      <div style={{padding:"14px 16px",display:"flex",flexDirection:"column",gap:11}}>

        {/* ── Verification gate for restricted categories ── */}
        {NEEDS_VERIFIED_CATS.includes(cat)&&!MOCK_USER.verified&&(
          <div style={{textAlign:"center",padding:"20px 16px"}}>
            <div style={{fontSize:36,marginBottom:8}}>🔒</div>
            <div style={{fontWeight:900,fontSize:15,color:C.text,marginBottom:6}}>Account Verification Required</div>
            <div style={{fontSize:12,color:C.muted,lineHeight:1.6,marginBottom:14}}>
              To post in <span style={{fontWeight:700,color:meta.color}}>{cat}</span>, your account must be verified by our admin team.
              {MOCK_USER.pendingReview?" Your verification is under review.":""}
            </div>
            {MOCK_USER.pendingReview
              ?<div style={{padding:"10px 14px",borderRadius:10,background:"#FFF7ED",border:"1px solid #FCD34D",fontSize:11,color:"#78350F",fontWeight:600}}>⏳ Verification in progress — we'll notify you by SMS once approved.</div>
              :<div style={{padding:"10px 14px",borderRadius:10,background:C.purpleFg,border:`1px solid ${C.purple}33`,fontSize:11,color:C.purple,fontWeight:600}}>→ Complete signup & submit your documents to get verified.</div>
            }
            <button onClick={resetAll} style={{marginTop:14,padding:"9px 20px",borderRadius:10,background:C.surface,border:`1px solid ${C.border}`,color:C.muted,fontWeight:700,fontSize:12,cursor:"pointer"}}>← Back</button>
          </div>
        )}

        {/* ── Review-queue notice for Safety/L&F/Missing (unverified) ── */}
        {REVIEW_QUEUE_CATS.includes(cat)&&!isMissing&&!MOCK_USER.verified&&(
          <div style={{padding:"10px 12px",borderRadius:10,background:"#FFF7ED",border:"1px solid #FCD34D",display:"flex",gap:8,alignItems:"flex-start"}}>
            <span style={{fontSize:16,flexShrink:0}}>⏳</span>
            <div style={{fontSize:11,color:"#78350F",lineHeight:1.5}}>
              <span style={{fontWeight:700}}>Pending verification:</span> Your post will be reviewed by our admin/customer support team before it's visible to the community. We prioritise safety and emergency posts.
            </div>
          </div>
        )}

        {/* Only show the form when allowed */}
        {(!NEEDS_VERIFIED_CATS.includes(cat)||MOCK_USER.verified)&&(
        <>

        {/* ── MISSING PERSON form ── */}
        {isMissing&&(
          <>
            {/* Child / Adult toggle */}
            <div>
              <div style={{fontSize:12,fontWeight:700,color:C.text,marginBottom:6}}>Who is missing?</div>
              <div style={{display:"flex",gap:6}}>
                {[["child","👶 Missing Child"],["adult","🧑 Missing Adult"]].map(([v,l])=>(
                  <button key={v} onClick={()=>setMissingType(v)}
                    style={{flex:1,padding:"9px",borderRadius:10,border:`2px solid ${missingType===v?C.crimson:C.border}`,background:missingType===v?C.crimsonL:"#fff",fontWeight:700,fontSize:12,color:missingType===v?C.crimson:C.muted,cursor:"pointer"}}>{l}</button>
                ))}
              </div>
            </div>
            {/* Name */}
            <div>
              <div style={{fontSize:12,fontWeight:700,color:C.text,marginBottom:5}}>Full Name <span style={{color:C.crimson}}>*</span></div>
              <input value={missingName} onChange={e=>setMissingName(e.target.value)}
                placeholder={missingType==="child"?"Child's full name…":"Person's full name…"}
                style={{width:"100%",padding:"9px 12px",borderRadius:10,border:`1.5px solid ${C.border}`,fontSize:13,outline:"none",boxSizing:"border-box",fontFamily:"inherit"}}/>
            </div>
            {/* Age + Physical description – side by side */}
            <div style={{display:"flex",gap:8}}>
              <div style={{flex:1}}>
                <div style={{fontSize:12,fontWeight:700,color:C.text,marginBottom:5}}>Age</div>
                <input value={missingAge} onChange={e=>setMissingAge(e.target.value)}
                  placeholder="e.g. 7 years"
                  style={{width:"100%",padding:"9px 12px",borderRadius:10,border:`1.5px solid ${C.border}`,fontSize:13,outline:"none",boxSizing:"border-box",fontFamily:"inherit"}}/>
              </div>
              <div style={{flex:2}}>
                <div style={{fontSize:12,fontWeight:700,color:C.text,marginBottom:5}}>Contact Number</div>
                <input value={missingContact} onChange={e=>setMissingContact(e.target.value)}
                  placeholder="Your mobile number"
                  style={{width:"100%",padding:"9px 12px",borderRadius:10,border:`1.5px solid ${C.border}`,fontSize:13,outline:"none",boxSizing:"border-box",fontFamily:"inherit"}}/>
              </div>
            </div>
            {/* Last seen */}
            <div>
              <div style={{fontSize:12,fontWeight:700,color:C.text,marginBottom:5}}>Last Seen Location & Time <span style={{color:C.crimson}}>*</span></div>
              <input value={missingLastSeen} onChange={e=>setMissingLastSeen(e.target.value)}
                placeholder="e.g. Park Gate C, GM Smondo – Today 3:30 PM"
                style={{width:"100%",padding:"9px 12px",borderRadius:10,border:`1.5px solid ${C.border}`,fontSize:13,outline:"none",boxSizing:"border-box",fontFamily:"inherit"}}/>
            </div>
            {/* Additional description */}
            <div>
              <div style={{fontSize:12,fontWeight:700,color:C.text,marginBottom:5}}>Physical Description / Clothing</div>
              <textarea value={draft} onChange={e=>handleDraft(e.target.value)} rows={2}
                placeholder="Describe clothing, features, anything that helps identify…"
                style={{width:"100%",padding:"9px 12px",borderRadius:10,border:`1.5px solid ${C.border}`,fontSize:13,outline:"none",resize:"vertical",fontFamily:"inherit",boxSizing:"border-box"}}/>
            </div>
          </>
        )}

        {/* ── Safety: urgency ── */}
        {cat==="Safety"&&(
          <div>
            <div style={{fontSize:12,fontWeight:700,color:C.text,marginBottom:6}}>🚨 Urgency Level</div>
            <div style={{display:"flex",gap:6}}>
              {[["high","🔴 High",C.coral],["medium","🟡 Medium",C.marigold],["low","🟢 Low",C.mint]].map(([v,l,c])=>(
                <button key={v} onClick={()=>setUrgency(v)}
                  style={{flex:1,padding:"6px",borderRadius:10,border:`2px solid ${urgency===v?c:C.border}`,background:urgency===v?`${c}18`:"#fff",fontWeight:700,fontSize:11,color:urgency===v?c:C.muted,cursor:"pointer"}}>{l}</button>
              ))}
            </div>
          </div>
        )}

        {/* ── Lost & Found: lost/found toggle ── */}
        {cat==="Lost & Found"&&(
          <div style={{display:"flex",gap:6}}>
            {[["lost","🔍 I Lost Something"],["found","✅ I Found Something"]].map(([v,l])=>(
              <button key={v} onClick={()=>setLostType(v)}
                style={{flex:1,padding:"8px",borderRadius:10,border:`2px solid ${lostType===v?C.marigold:C.border}`,background:lostType===v?C.marigoldL:"#fff",fontWeight:700,fontSize:12,color:lostType===v?C.text:C.muted,cursor:"pointer"}}>{l}</button>
            ))}
          </div>
        )}

        {/* ── Text content (non-missing) ── */}
        {!isMissing&&(
          <>
            {blocked&&<ContentBlockedBanner context="post" onEdit={()=>{setDraft("");setBlocked(false);}}/>}
            {!blocked&&(
              <PIITextarea value={draft} onChange={handleDraft} rows={3}
                placeholder={
                  cat==="Safety"?"Describe the safety concern, location, and what residents should do…":
                  cat==="Lost & Found"?lostType==="lost"?"What did you lose? Describe item, last seen location, and how to contact you…":"What did you find? Describe item, where you found it, how to reach you…":
                  cat==="Recommendation"?"Who or what are you recommending? Share name, location, and why…":
                  cat==="Services"?"Describe the service, provider name, contact, and your experience…":
                  "What's happening in your neighbourhood?"
                }/>
            )}
          </>
        )}

        {/* ── Image upload (Missing Person + Lost & Found) ── */}
        {(isMissing||isLF)&&(
          <ImageUpload images={images} onChange={setImages}
            label={isMissing?"Photo of Missing Person":"Photo of Lost/Found Item"}
            maxImages={isMissing?3:4}/>
        )}

        {/* ── Notification channel preview (alert categories) ── */}
        {isAlert&&(
          <div style={{padding:"10px 12px",borderRadius:10,background:isMissing?C.crimsonL:cat==="Safety"?C.coralL:C.marigoldL,border:`1px solid ${(isMissing?C.crimson:cat==="Safety"?C.coral:C.marigold)}33`}}>
            <div style={{fontSize:11,fontWeight:700,color:isMissing?C.crimson:cat==="Safety"?C.coral:C.marigold,marginBottom:6}}>
              {isMissing?"🔊 How this alert will reach EC Phase 2 members:":"🔔 How this alert will reach EC Phase 2 members:"}
            </div>
            <div style={{display:"flex",flexWrap:"wrap",gap:5}}>
              {["📱 App push notification","📧 Email to all members","💬 SMS to all members",...(isMissing?["🔊 Urgent tone on all devices"]:["📡 Share with nearby areas"])].map(ch=>(
                <span key={ch} style={{fontSize:10,fontWeight:700,padding:"3px 8px",borderRadius:99,background:"rgba(255,255,255,0.7)",color:C.text}}>{ch}</span>
              ))}
            </div>
          </div>
        )}

        <div style={{display:"flex",gap:8}}>
          <button onClick={resetAll} style={{flex:1,padding:"10px",borderRadius:12,background:C.surface,color:C.muted,fontWeight:700,fontSize:13,border:`1.5px solid ${C.border}`,cursor:"pointer"}}>Cancel</button>
          <button onClick={doPost}
            style={{flex:1,padding:"10px",borderRadius:12,background:!canPost?C.border:meta.color||C.purple,color:!canPost?C.muted:"#fff",fontWeight:900,fontSize:13,border:"none",cursor:"pointer"}}>
            {blocked?"🚫 Blocked":isMissing?"🆘 Send Urgent Alert":isAlert?"🚨 Post & Alert":"Post"}
          </button>
        </div>

        </> /* end allowed-to-post wrapper */
        )}
      </div>
    </div>
  );
}

// ─── Promotion Modal ──────────────────────────────────────────────────────────
function PromotionModal({bizName, onClose}){
  const [sel,setSel]=useState(null);
  const [paid,setPaid]=useState(false);

  if(paid) return(
    <div style={{position:"fixed",inset:0,zIndex:300,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(26,16,51,0.65)",backdropFilter:"blur(6px)",padding:"0 16px"}}>
      <div style={{width:"100%",maxWidth:360,background:"#fff",borderRadius:24,padding:"28px 24px",textAlign:"center"}}>
        <div style={{fontSize:48,marginBottom:10}}>🎉</div>
        <div style={{fontWeight:900,fontSize:18,color:C.text}}>Promotion Active!</div>
        <div style={{fontSize:13,color:C.muted,marginTop:6,lineHeight:1.5}}>
          <span style={{fontWeight:700,color:C.purple}}>{bizName}</span> is now promoted as a
          <span style={{fontWeight:700,color:PROMO_TIERS.find(t=>t.tier===sel)?.color}}> {PROMO_TIERS.find(t=>t.tier===sel)?.label} </span>
          for today. Verified residents of EC Phase 2 will see your promotion.
        </div>
        <div style={{margin:"16px 0",padding:"12px 16px",borderRadius:12,background:C.surface,border:`1px solid ${C.border}`,display:"flex",justifyContent:"space-between",fontSize:12}}>
          <span style={{color:C.muted}}>Amount paid</span>
          <span style={{fontWeight:900,color:C.purple}}>₹{sel}</span>
        </div>
        <div style={{fontSize:11,color:C.muted,marginBottom:16}}>Valid: Today only (24 hours from now)</div>
        <button onClick={onClose} style={{width:"100%",padding:"12px",borderRadius:14,background:C.purple,color:"#fff",fontWeight:900,fontSize:14,border:"none",cursor:"pointer"}}>Done</button>
      </div>
    </div>
  );

  return(
    <div style={{position:"fixed",inset:0,zIndex:300,display:"flex",alignItems:"flex-end",justifyContent:"center",background:"rgba(26,16,51,0.6)",backdropFilter:"blur(5px)"}}>
      <div style={{width:"100%",maxWidth:430,background:"#fff",borderRadius:"24px 24px 0 0",paddingBottom:32,maxHeight:"90vh",overflowY:"auto"}}>
        <div style={{display:"flex",justifyContent:"center",padding:"12px 0 4px"}}><div style={{width:40,height:4,borderRadius:99,background:C.border}}/></div>
        <div style={{padding:"10px 20px 14px",borderBottom:`1px solid ${C.border}`}}>
          <div style={{fontWeight:900,fontSize:16,color:C.text}}>Promote Your Business</div>
          <div style={{fontSize:12,color:C.muted,marginTop:2}}>{bizName} · Choose a 1-day promotion plan</div>
        </div>
        <div style={{padding:"14px 16px",display:"flex",flexDirection:"column",gap:10}}>
          {PROMO_TIERS.map(t=>{
            const on=sel===t.tier;
            return(
              <button key={t.tier} onClick={()=>setSel(t.tier)}
                style={{display:"flex",alignItems:"flex-start",gap:12,padding:"14px 14px",borderRadius:16,border:`2px solid ${on?t.color:C.border}`,background:on?t.colorL:"#fff",cursor:"pointer",textAlign:"left",transition:"all 0.15s"}}>
                <div style={{width:40,height:40,borderRadius:12,background:on?t.color:"#F3F4F6",display:"flex",alignItems:"center",justifyContent:"center",fontSize:20,flexShrink:0}}>{t.icon}</div>
                <div style={{flex:1}}>
                  <div style={{display:"flex",alignItems:"center",gap:6}}>
                    <span style={{fontWeight:900,fontSize:14,color:on?t.color:C.text}}>₹{t.tier}</span>
                    <span style={{fontSize:11,fontWeight:700,padding:"2px 7px",borderRadius:99,background:on?t.color+"22":"#F3F4F6",color:on?t.color:C.muted}}>{t.label}</span>
                  </div>
                  <div style={{fontSize:11,color:C.muted,marginTop:3,lineHeight:1.4}}>{t.desc}</div>
                  <div style={{display:"flex",flexWrap:"wrap",gap:4,marginTop:6}}>
                    {t.perks.map(p=>(
                      <span key={p} style={{fontSize:9,fontWeight:700,padding:"2px 6px",borderRadius:99,background:on?t.color+"18":"#F9FAFB",color:on?t.color:C.muted,border:`1px solid ${on?t.color+"33":C.border}`}}>✓ {p}</span>
                    ))}
                  </div>
                </div>
                <div style={{width:20,height:20,borderRadius:99,border:`2px solid ${on?t.color:C.border}`,background:on?t.color:"#fff",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:2}}>
                  {on&&<span style={{color:"#fff",fontSize:10,fontWeight:900}}>✓</span>}
                </div>
              </button>
            );
          })}
        </div>
        <div style={{padding:"4px 16px 0",display:"flex",flexDirection:"column",gap:8}}>
          <div style={{padding:"10px 14px",borderRadius:12,background:C.surface,border:`1px solid ${C.border}`,fontSize:11,color:C.muted,lineHeight:1.5}}>
            ℹ️ All promotions are valid for <span style={{fontWeight:700}}>1 day only</span>. ₹500 posts appear in the feed sidebar (ordered by posting time). ₹250 and ₹100 posts appear within the main feed, ordered by tier then time.
          </div>
          <button onClick={()=>{if(sel)setPaid(true);}}
            style={{width:"100%",padding:"13px",borderRadius:14,background:sel?PROMO_TIERS.find(t=>t.tier===sel)?.color||C.purple:C.border,color:sel?"#fff":C.muted,fontWeight:900,fontSize:14,border:"none",cursor:"pointer"}}>
            {sel?`Pay ₹${sel} & Activate`:"Select a plan above"}
          </button>
          <button onClick={onClose} style={{width:"100%",padding:"11px",borderRadius:14,background:C.surface,color:C.muted,fontWeight:700,fontSize:13,border:`1px solid ${C.border}`,cursor:"pointer"}}>Cancel</button>
        </div>
      </div>
    </div>
  );
}


// ── ReportSheet ──────────────────────────────────────────
function ReportSheet({type,name,onClose}){
  const [selected,setSelected]=useState(null);
  const [done,setDone]=useState(false);
  const reasons=type==="post"
    ?["Misinformation / Fake News","Spam or Scam","Harassment","Hate Speech","Inappropriate Content","Other"]
    :["Harassment or Bullying","Impersonation / Fake Account","Spam","Threatening Behaviour","Sharing Personal Info","Other"];
  if(done)return(
    <div style={{position:"fixed",inset:0,zIndex:400,background:"rgba(10,0,20,0.65)",display:"flex",alignItems:"flex-end"}}>
      <div style={{width:"100%",background:"#fff",borderRadius:"28px 28px 0 0",padding:"32px 24px 44px",textAlign:"center"}}>
        <div style={{fontSize:52,marginBottom:10}}>✅</div>
        <div style={{fontWeight:900,fontSize:18,color:"#18103A",marginBottom:6}}>Report Submitted</div>
        <div style={{fontSize:13,color:"#7C7290",marginBottom:24,lineHeight:1.6}}>We'll review this and take action within 24 hours. Thank you for keeping the community safe.</div>
        <button onClick={onClose} style={{width:"100%",padding:"14px",borderRadius:16,background:"#5C2D91",color:"#fff",fontWeight:900,fontSize:15,border:"none",cursor:"pointer"}}>Done</button>
      </div>
    </div>
  );
  return(
    <div style={{position:"fixed",inset:0,zIndex:400,background:"rgba(10,0,20,0.65)",display:"flex",alignItems:"flex-end"}} onClick={onClose}>
      <div style={{width:"100%",background:"#fff",borderRadius:"28px 28px 0 0",padding:"24px 20px 44px"}} onClick={e=>e.stopPropagation()}>
        <div style={{width:44,height:5,borderRadius:99,background:"#ECEAF4",margin:"0 auto 22px"}}/>
        <div style={{fontWeight:900,fontSize:17,color:"#18103A",marginBottom:3}}>Report {type==="post"?"Post":"@"+name}</div>
        <div style={{fontSize:12,color:"#7C7290",marginBottom:18}}>Help us understand what's wrong with this {type}.</div>
        <div style={{display:"flex",flexDirection:"column",gap:9}}>
          {reasons.map(r=>(
            <button key={r} onClick={()=>setSelected(r)}
              style={{padding:"12px 16px",borderRadius:14,textAlign:"left",border:`1.5px solid ${selected===r?"#B91C1C":"#ECEAF4"}`,background:selected===r?"#FEF2F2":"#fff",cursor:"pointer",fontSize:13,fontWeight:selected===r?700:500,color:selected===r?"#B91C1C":"#18103A",display:"flex",alignItems:"center",justifyContent:"space-between",transition:"all 0.15s"}}>
              {r}{selected===r&&<span style={{color:"#B91C1C",fontSize:16}}>●</span>}
            </button>
          ))}
        </div>
        <button onClick={()=>selected&&setDone(true)}
          style={{marginTop:18,width:"100%",padding:"14px",borderRadius:16,background:selected?"#B91C1C":"#E5E5E5",color:selected?"#fff":"#aaa",fontWeight:900,fontSize:14,border:"none",cursor:selected?"pointer":"default",transition:"all 0.2s"}}>
          Submit Report
        </button>
      </div>
    </div>
  );
}

// ── UserProfileSheet ─────────────────────────────────────
function UserProfileSheet({person,onClose,onBlock,onReport}){
  const mutualPosts=Math.floor(Math.random()*15)+3;
  return(
    <div style={{position:"fixed",inset:0,zIndex:400,background:"rgba(10,0,20,0.65)",display:"flex",alignItems:"flex-end"}} onClick={onClose}>
      <div style={{width:"100%",background:"#fff",borderRadius:"28px 28px 0 0",paddingBottom:44}} onClick={e=>e.stopPropagation()}>
        {/* Handle */}
        <div style={{width:44,height:5,borderRadius:99,background:"#ECEAF4",margin:"12px auto 0"}}/>
        {/* Cover gradient */}
        <div style={{height:80,background:`linear-gradient(135deg,${person.avC},${person.avC}88)`,margin:"12px 0 0",position:"relative"}}>
          <div style={{position:"absolute",bottom:-28,left:20,width:56,height:56,borderRadius:18,background:`linear-gradient(135deg,${person.avC},${person.avC}BB)`,display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:900,fontSize:20,border:"3px solid #fff",boxShadow:`0 4px 16px ${person.avC}55`}}>{person.av}</div>
        </div>
        {/* Info */}
        <div style={{padding:"36px 20px 16px"}}>
          <div style={{display:"flex",alignItems:"flex-start",justifyContent:"space-between",marginBottom:4}}>
            <div>
              <div style={{fontSize:18,fontWeight:900,color:"#18103A"}}>{person.name}</div>
              <div style={{fontSize:12,color:"#7C7290",marginTop:2}}>✓ Verified Resident · EC Phase 1</div>
            </div>
            <span style={{fontSize:10,fontWeight:800,padding:"4px 10px",borderRadius:99,background:"#ECFDF5",color:"#059669",border:"1px solid #A7F3D0"}}>✓ Aadhaar</span>
          </div>
          {/* Stats row */}
          <div style={{display:"flex",gap:0,marginTop:14,borderRadius:16,overflow:"hidden",border:"1.5px solid #ECEAF4"}}>
            {[["🏘","Prestige Sunrise\nPark · B-304"],["📝",`${mutualPosts} posts`],["🤝","128\nconnections"]].map(([ic,val],i)=>(
              <div key={i} style={{flex:1,padding:"12px 8px",textAlign:"center",borderLeft:i>0?"1.5px solid #ECEAF4":"none"}}>
                <div style={{fontSize:18,marginBottom:4}}>{ic}</div>
                <div style={{fontSize:10,fontWeight:700,color:"#18103A",whiteSpace:"pre-line",lineHeight:1.3}}>{val}</div>
              </div>
            ))}
          </div>
          {/* Member since */}
          <div style={{marginTop:12,padding:"10px 14px",borderRadius:13,background:"#F5F4F7",display:"flex",alignItems:"center",gap:10}}>
            <span style={{fontSize:15}}>📅</span>
            <div>
              <div style={{fontSize:11,fontWeight:700,color:"#18103A"}}>Member since Jan 2024</div>
              <div style={{fontSize:10,color:"#7C7290"}}>Active in EC Phase 1 community</div>
            </div>
          </div>
          {/* Action buttons */}
          <div style={{display:"flex",gap:10,marginTop:14}}>
            <button onClick={onClose} style={{flex:1,padding:"12px",borderRadius:14,background:"#F3EBFF",color:"#5C2D91",fontWeight:900,fontSize:13,border:"none",cursor:"pointer"}}>💬 Message</button>
            <button onClick={()=>{onClose();onReport();}} style={{padding:"12px 16px",borderRadius:14,background:"#FFF7EC",color:"#D97706",fontWeight:700,fontSize:13,border:"none",cursor:"pointer"}}>⚑ Report</button>
            <button onClick={()=>{onClose();onBlock();}} style={{padding:"12px 16px",borderRadius:14,background:"#FFF0F1",color:"#FF6B7A",fontWeight:700,fontSize:13,border:"none",cursor:"pointer"}}>🚫 Block</button>
          </div>
        </div>
      </div>
    </div>
  );
}

// ── BlockConfirmSheet ─────────────────────────────────────
function BlockConfirmSheet({name,onConfirm,onClose}){
  const [done,setDone]=useState(false);
  if(done)return(
    <div style={{position:"fixed",inset:0,zIndex:400,background:"rgba(10,0,20,0.65)",display:"flex",alignItems:"flex-end"}}>
      <div style={{width:"100%",background:"#fff",borderRadius:"28px 28px 0 0",padding:"32px 24px 44px",textAlign:"center"}}>
        <div style={{fontSize:52,marginBottom:10}}>🚫</div>
        <div style={{fontWeight:900,fontSize:18,color:"#18103A",marginBottom:6}}>{name} Blocked</div>
        <div style={{fontSize:13,color:"#7C7290",marginBottom:24,lineHeight:1.6}}>You won't see their posts or messages. You can unblock them anytime from Privacy & Safety settings.</div>
        <button onClick={onClose} style={{width:"100%",padding:"14px",borderRadius:16,background:"#FF6B7A",color:"#fff",fontWeight:900,fontSize:15,border:"none",cursor:"pointer"}}>OK</button>
      </div>
    </div>
  );
  return(
    <div style={{position:"fixed",inset:0,zIndex:400,background:"rgba(10,0,20,0.65)",display:"flex",alignItems:"flex-end"}} onClick={onClose}>
      <div style={{width:"100%",background:"#fff",borderRadius:"28px 28px 0 0",padding:"28px 20px 44px"}} onClick={e=>e.stopPropagation()}>
        <div style={{width:44,height:5,borderRadius:99,background:"#ECEAF4",margin:"0 auto 22px"}}/>
        <div style={{fontSize:48,textAlign:"center",marginBottom:14}}>🚫</div>
        <div style={{fontWeight:900,fontSize:17,color:"#18103A",textAlign:"center",marginBottom:8}}>Block {name}?</div>
        <div style={{fontSize:13,color:"#7C7290",textAlign:"center",marginBottom:24,lineHeight:1.7,padding:"0 8px"}}>They won't be able to message you, see your posts, or find your profile. You can unblock them anytime.</div>
        <div style={{display:"flex",gap:10}}>
          <button onClick={onClose} style={{flex:1,padding:"13px",borderRadius:14,background:"#F5F4F7",color:"#18103A",fontWeight:700,fontSize:14,border:"1px solid #ECEAF4",cursor:"pointer"}}>Cancel</button>
          <button onClick={()=>{onConfirm();setDone(true)}} style={{flex:1,padding:"13px",borderRadius:14,background:"#FF6B7A",color:"#fff",fontWeight:900,fontSize:14,border:"none",cursor:"pointer"}}>Block</button>
        </div>
      </div>
    </div>
  );
}

function StoryViewer({story,onClose}){
  const isOwn=story==="own";
  const name=isOwn?"Your Story":story.name;
  const inits=isOwn?"MT":story.init;
  const col=isOwn?C.purple:story.c;
  const idx=isOwn?0:Math.abs((story.init.charCodeAt(0)+story.init.charCodeAt(1)*3)%6);
  const CONTENT=[
    {emoji:"🌅",text:"Beautiful sunset from our terrace today! EC Phase 2 ✨"},
    {emoji:"🌺",text:"Community garden is blooming! Thanks to all volunteers 🌿"},
    {emoji:"🐕",text:"Morning walk at the EC park. These green spaces are a blessing! 🌳"},
    {emoji:"🎉",text:"Kids had the best time at the cricket match. What a community! 🏏"},
    {emoji:"☕",text:"New café near Prestige Junction — highly recommend the filter coffee! ☕"},
    {emoji:"🏡",text:"Our complex looks so clean today. Thank you housekeeping team! ✨"},
  ];
  const sc=CONTENT[idx];
  const [progress,setProgress]=useState(0);
  useEffect(()=>{
    if(isOwn) return;
    const t=setInterval(()=>{
      setProgress(p=>{
        if(p>=100){clearInterval(t);setTimeout(onClose,200);return 100;}
        return p+1.67;
      });
    },100);
    return ()=>clearInterval(t);
  },[]);
  return(
    <div style={{position:"fixed",inset:0,zIndex:200,background:"#0a0014",display:"flex",flexDirection:"column",overflow:"hidden"}}>
      <div style={{position:"absolute",top:12,left:14,right:14,height:3,borderRadius:99,background:"rgba(255,255,255,0.2)"}}>
        <div style={{height:"100%",borderRadius:99,background:"#fff",width:isOwn?"100%":`${progress}%`,transition:"width 0.1s linear"}}/>
      </div>
      <div style={{position:"absolute",top:26,left:14,right:14,display:"flex",alignItems:"center",gap:12}}>
        <div style={{width:36,height:36,borderRadius:11,background:`linear-gradient(135deg,${col},${col}99)`,display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:900,fontSize:13,border:"2px solid rgba(255,255,255,0.5)",flexShrink:0}}>{inits}</div>
        <div style={{flex:1}}>
          <div style={{fontWeight:800,fontSize:13,color:"#fff"}}>{name}</div>
          <div style={{fontSize:10,color:"rgba(255,255,255,0.6)"}}>EC Phase 2 · {isOwn?"Now":"2h ago"}</div>
        </div>
        <button onClick={onClose} style={{width:30,height:30,borderRadius:99,background:"rgba(255,255,255,0.15)",border:"none",color:"#fff",fontWeight:900,fontSize:15,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"}}>✕</button>
      </div>
      <div style={{flex:1,display:"flex",alignItems:"center",justifyContent:"center",background:`linear-gradient(160deg,${col}55 0%,#0a0014 65%)`}}>
        {isOwn?(
          <div style={{textAlign:"center",padding:"0 32px"}}>
            <div style={{fontSize:64,marginBottom:16}}>📸</div>
            <div style={{color:"#fff",fontWeight:800,fontSize:18,marginBottom:8}}>Share a Moment</div>
            <div style={{color:"rgba(255,255,255,0.6)",fontSize:14,lineHeight:1.6}}>Tap to add a photo or update for your neighbours</div>
            <button onClick={onClose} style={{marginTop:24,padding:"11px 28px",borderRadius:14,background:`linear-gradient(135deg,#5C2D91,#8B5CF6)`,color:"#fff",fontWeight:800,fontSize:14,border:"none",cursor:"pointer"}}>📷 Add Story</button>
          </div>
        ):(
          <div style={{textAlign:"center",padding:"0 28px"}}>
            <div style={{fontSize:64,marginBottom:16}}>{sc.emoji}</div>
            <div style={{color:"#fff",fontWeight:700,fontSize:15,lineHeight:1.6}}>{sc.text}</div>
            {story.live&&<div style={{marginTop:16,display:"inline-flex",alignItems:"center",gap:6,padding:"5px 14px",borderRadius:99,background:"rgba(0,184,159,0.2)",border:"1px solid #00B89F55"}}>
              <div style={{width:7,height:7,borderRadius:"50%",background:"#00B89F"}}/>
              <span style={{color:"#00B89F",fontWeight:700,fontSize:11}}>Live · Active Now</span>
            </div>}
          </div>
        )}
      </div>
      {!isOwn&&(
        <div style={{padding:"16px 20px 32px",display:"flex",gap:10,justifyContent:"center"}}>
          {["👍","❤️","😮","🙏"].map(e=>(
            <button key={e} onClick={onClose} style={{width:50,height:50,borderRadius:14,background:"rgba(255,255,255,0.1)",border:"1px solid rgba(255,255,255,0.15)",fontSize:22,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"}}>{e}</button>
          ))}
        </div>
      )}
    </div>
  );
}

function FeedScreen(){
  const [storyOpen,setStoryOpen]=useState(null);
  const [reactions,setReactions]=useState({});          // {postId: reactionId}
  const [cat,setCat]=useState("All");
  const [feedPosts,setFeedPosts]=useState(POSTS);
  const [alerts,setAlerts]=useState([]);                // active notification toasts
  const [crossShare,setCrossShare]=useState(null);      // pending cross-share after alert post
  const [dispatch,setDispatch]=useState(null);          // pending dispatch modal {category, memberCount}
  const [removedPosts,setRemovedPosts]=useState(new Set()); // admin-removed cross-shared post IDs
  const [promotionFor,setPromotionFor]=useState(null);  // bizName | null — which business is promoting
  const [bizPromos,setBizPromos]=useState(BIZ_POSTS);
  const [postMenu,setPostMenu]=useState(null);           // postId with open ⋮ menu
  const [blockedAuthors,setBlockedAuthors]=useState(new Set());
  const [reportSheet,setReportSheet]=useState(null);     // {postId,author} | null
  const [blockSheet,setBlockSheet]=useState(null);       // {author} | null   // business promoted posts (can add more)

  const cats=["All",...Object.keys(CAT_META)];

  // Sort business promo posts: ₹500 → sidebar; in feed: ₹250 first, then ₹100, same-tier by promoTime
  const sidebar500=bizPromos.filter(b=>b.promoTier===500).sort((a,b)=>a.promoTime-b.promoTime);
  const feed250=bizPromos.filter(b=>b.promoTier===250).sort((a,b)=>a.promoTime-b.promoTime);
  const feed100=bizPromos.filter(b=>b.promoTier===100).sort((a,b)=>a.promoTime-b.promoTime);

  const basePosts=cat==="All"?feedPosts:feedPosts.filter(p=>p.category===cat);

  // Build final feed:
  //   • ₹250 posts pinned at top (in order of posting time)
  //   • Then regular posts, with one ₹100 post injected after every 2nd regular post
  const buildFeed=()=>{
    const items=[];
    feed250.forEach(b=>items.push({_type:"biz",_tier:250,...b}));
    let b100idx=0;
    basePosts.forEach((post,i)=>{
      items.push({_type:"post",...post});
      if(cat==="All"&&(i+1)%2===0&&b100idx<feed100.length){
        items.push({_type:"biz",_tier:100,...feed100[b100idx++]});
      }
    });
    return items;
  };
  const feedItems=buildFeed();

  // Called by PostComposer when user submits a post
  const handlePost=(postData)=>{
    const {category,content,...extra}=postData;
    const newPost={
      id:Date.now(), author:"Meena T.", av:"MT", avC:C.purple,
      apartment:"Prestige Sunrise Park", time:"Just now",
      category, content, likes:0, comments:0, sharedFrom:null,
      ...extra,
    };
    setFeedPosts(p=>[newPost,...p]);
    // All alert categories → show dispatch modal + queue toast + queue cross-share
    if(ALERT_CATEGORIES.includes(category)){
      setDispatch({id:newPost.id, category, content, memberCount:247});
    }
  };

  // DispatchModal "Got it" / "Share with nearby areas" → open CrossShareModal
  const handleDispatchDone=()=>{
    if(dispatch){
      const alertId=Date.now()+"a";
      setAlerts(a=>[...a,{
        id:alertId, cat:dispatch.category, area:"EC Phase 2",
        content:dispatch.content, author:"Meena T.", memberCount:dispatch.memberCount, sharedAreas:[],
      }]);
      setCrossShare({id:dispatch.id, category:dispatch.category, content:dispatch.content});
    }
    setDispatch(null);
  };

  // After cross-share modal: update alert badge + mark post as shared
  const handleShare=(areas)=>{
    if(crossShare){
      setAlerts(a=>a.map(x=>x.content===crossShare.content?{...x,sharedAreas:areas}:x));
      setFeedPosts(p=>p.map(x=>x.id===crossShare.id?{...x,sharedAreas:areas}:x));
    }
    setCrossShare(null);
  };
  const handleSkip=()=>setCrossShare(null);

  // React to a post
  const handleReact=(postId,reactionId)=>{
    setReactions(r=>reactionId?{...r,[postId]:reactionId}:(({[postId]:_,...rest})=>rest)(r));
  };

  // Community admin removes a cross-shared post from this community
  const adminRemove=(postId)=>setRemovedPosts(s=>new Set([...s,postId]));

  return(
    <div style={{background:"#F0F2F5",minHeight:"100vh"}}>
      {storyOpen&&<StoryViewer story={storyOpen} onClose={()=>setStoryOpen(null)}/>}
      {/* ── Instant notification toasts ── */}
      <NotificationToast alerts={alerts} onDismiss={(id)=>setAlerts(a=>a.filter(x=>x.id!==id))}/>

      {/* ── Dispatch confirmation modal (shown immediately after alert post) ── */}
      {dispatch&&<DispatchModal category={dispatch.category} memberCount={dispatch.memberCount} onDone={handleDispatchDone}/>}

      {/* ── Cross-share modal (appears after Safety/L&F/Missing post) ── */}
      {crossShare&&<CrossShareModal category={crossShare.category} onShare={handleShare} onSkip={handleSkip}/>}

      {/* ── Promotion modal ── */}
      {promotionFor&&<PromotionModal bizName={promotionFor} onClose={()=>setPromotionFor(null)}/>}

      {/* ── ₹500 FEATURED SIDEBAR STRIP ── */}
      {sidebar500.length>0&&(
        <div className="mx-3 mt-3">
          <div style={{background:"linear-gradient(135deg,#FFFBEB,#FEF3C7)",border:`1.5px solid ${C.marigold}`,borderRadius:16,overflow:"hidden"}}>
            <div style={{padding:"8px 14px",borderBottom:`1px solid ${C.marigold}33`,display:"flex",alignItems:"center",justifyContent:"space-between"}}>
              <div style={{display:"flex",alignItems:"center",gap:6}}>
                <span style={{fontSize:14}}>⭐</span>
                <span style={{fontSize:12,fontWeight:900,color:"#92400E"}}>FEATURED BUSINESSES</span>
              </div>
              <span style={{fontSize:10,color:"#B45309",fontWeight:600}}>Verified Businesses</span>
            </div>
            {sidebar500.map((biz,i)=>(
              <div key={biz.id} style={{padding:"12px 14px",borderBottom:i<sidebar500.length-1?`1px solid ${C.marigold}22`:"none",display:"flex",gap:10,alignItems:"flex-start"}}>
                <div style={{width:40,height:40,borderRadius:10,background:biz.avC,display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:900,fontSize:12,flexShrink:0}}>{biz.av}</div>
                <div style={{flex:1}}>
                  <div style={{display:"flex",alignItems:"center",gap:5}}>
                    <span style={{fontSize:13,fontWeight:900,color:"#1A1033"}}>{biz.bizName}</span>
                    {biz.verified&&<span style={{fontSize:9,fontWeight:800,padding:"1px 5px",borderRadius:99,background:"#ECFDF5",color:"#059669"}}>✓ Verified</span>}
                  </div>
                  <div style={{fontSize:10,color:C.muted,marginBottom:4}}>{biz.bizType} · {biz.area}</div>
                  <div style={{fontSize:12,color:"#374151",lineHeight:1.4}}>{biz.content}</div>
                  <div style={{marginTop:5,fontSize:10,fontWeight:600,color:"#92400E"}}>📞 {biz.contact}</div>
                </div>
                <button onClick={()=>setPromotionFor(biz.bizName)}
                  style={{fontSize:9,fontWeight:700,padding:"3px 7px",borderRadius:6,background:C.marigoldL,color:"#92400E",border:"1px solid #F59E0B",cursor:"pointer",flexShrink:0}}>⭐ Promote</button>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* ── Report / Block overlays ── */}
      {reportSheet&&<ReportSheet type="post" name={reportSheet.author} onClose={()=>setReportSheet(null)}/>}
      {blockSheet&&<BlockConfirmSheet name={blockSheet.author} onConfirm={()=>setBlockedAuthors(s=>{const n=new Set(s);n.add(blockSheet.author);return n;})} onClose={()=>setBlockSheet(null)}/>}
      {/* ⋮ post menu backdrop */}
      {postMenu&&<div style={{position:"fixed",inset:0,zIndex:90}} onClick={()=>setPostMenu(null)}/>}

      {/* ── Feed greeting header ── */}
      <div style={{padding:"14px 16px 6px",display:"flex",alignItems:"center",justifyContent:"space-between"}}>
        <div>
          <div style={{fontSize:11,fontWeight:600,color:"#7C7290",letterSpacing:"0.02em"}}>MYTOWN 360 · EC PHASE 1</div>
          <div style={{fontSize:18,fontWeight:900,color:"#18103A",marginTop:1}}>Good morning, Meena! 👋</div>
        </div>
        <div style={{display:"flex",gap:8,alignItems:"center"}}>
          <button style={{width:38,height:38,borderRadius:12,background:"#F3EBFF",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontSize:17}}>🔍</button>
          <div style={{position:"relative"}}>
            <button style={{width:38,height:38,borderRadius:12,background:"#F3EBFF",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontSize:17}}>🔔</button>
            <span style={{position:"absolute",top:-3,right:-3,width:16,height:16,borderRadius:"50%",background:"#E11D48",color:"#fff",fontSize:9,fontWeight:900,display:"flex",alignItems:"center",justifyContent:"center",border:"2px solid #fff"}}>3</span>
          </div>
        </div>
      </div>

      {/* ── Story / Neighbours strip ── */}
      <div style={{overflowX:"auto",padding:"12px 14px 4px",scrollbarWidth:"none"}}>
        <div style={{display:"flex",gap:10,width:"max-content"}}>
          {/* Add Story tile */}
          <div onClick={()=>setStoryOpen("own")} style={{display:"flex",flexDirection:"column",alignItems:"center",gap:5,cursor:"pointer"}}>
            <div style={{
              width:56,height:56,borderRadius:18,
              background:"linear-gradient(135deg,#F3EBFF,#EAE0FF)",
              border:`2px dashed ${C.purple}55`,
              display:"flex",alignItems:"center",justifyContent:"center",
              fontSize:22,
            }}>＋</div>
            <span style={{fontSize:10,fontWeight:700,color:C.purple}}>Your Story</span>
          </div>
          {[
            {init:"RA",c:"#4F46E5",name:"Rahul A.",live:true},
            {init:"PS",c:"#D97706",name:"Priya S.",live:false},
            {init:"KM",c:"#059669",name:"Kiran M.",live:true},
            {init:"SW",c:"#E11D48",name:"Sunita W.",live:false},
            {init:"VR",c:"#0284C7",name:"Vijay R.",live:true},
            {init:"AM",c:"#7C3AED",name:"Asha M.",live:false},
          ].map(s=>(
            <div key={s.init} onClick={()=>setStoryOpen(s)} style={{display:"flex",flexDirection:"column",alignItems:"center",gap:5,cursor:"pointer"}}>
              <div style={{position:"relative"}}>
                <div style={{
                  width:56,height:56,borderRadius:18,
                  background:`linear-gradient(135deg,${s.c},${s.c}99)`,
                  display:"flex",alignItems:"center",justifyContent:"center",
                  color:"#fff",fontWeight:900,fontSize:17,
                  border:`2.5px solid ${s.live?"#00B89F":"transparent"}`,
                  boxShadow:s.live?`0 0 0 2px #fff, 0 0 0 4px #00B89F`:`0 2px 8px ${s.c}44`,
                }}>{s.init}</div>
                {s.live&&<span style={{
                  position:"absolute",bottom:0,right:0,
                  width:14,height:14,borderRadius:"50%",
                  background:"#00B89F",border:"2px solid #fff",
                }}/>}
              </div>
              <span style={{fontSize:10,fontWeight:600,color:C.muted,maxWidth:56,textAlign:"center",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{s.name}</span>
            </div>
          ))}
        </div>
      </div>

      {/* ── Pinned community alert banner — compact ── */}
      <div style={{margin:"8px 14px 0",borderRadius:14,padding:"10px 14px",display:"flex",gap:10,alignItems:"center",background:"linear-gradient(135deg,#FFF1F2,#FFE4E7)",border:`1.5px solid ${C.coral}40`,boxShadow:"0 2px 8px rgba(244,63,94,0.1)"}}>
        <div style={{width:32,height:32,borderRadius:10,background:"linear-gradient(135deg,#E11D48,#FF6B7A)",display:"flex",alignItems:"center",justifyContent:"center",fontSize:15,flexShrink:0}}>⚠️</div>
        <div style={{flex:1,minWidth:0}}>
          <div style={{fontSize:12,fontWeight:900,color:"#BE123C"}}>Active Alert · Prestige Sunrise Park</div>
          <div style={{fontSize:11,color:"#9F1239",marginTop:1}}>Suspicious activity reported. Stay alert.</div>
        </div>
        <span style={{fontSize:18,color:"#E11D48"}}>›</span>
      </div>

      {/* ── Post Composer ── */}
      <div style={{margin:"10px 14px 0"}}>
        <PostComposer onPost={handlePost}/>
      </div>

      {/* ── Category filter chips ── */}
      <div style={{overflowX:"auto",padding:"10px 14px 4px",scrollbarWidth:"none"}}>
        <div style={{display:"flex",gap:7,width:"max-content"}}>
          {cats.map(c=>{
            const m=CAT_META[c];const active=cat===c;
            return(
              <button key={c} onClick={()=>setCat(c)}
                style={{
                  padding:"6px 14px",borderRadius:99,fontSize:11,fontWeight:800,
                  whiteSpace:"nowrap",border:"none",cursor:"pointer",
                  display:"flex",alignItems:"center",gap:5,
                  background:active
                    ? (m?`linear-gradient(135deg,${m.color},${m.color}CC)`:`linear-gradient(135deg,${C.purple},${C.purpleL})`)
                    : "#fff",
                  color:active?"#fff":C.muted,
                  boxShadow:active
                    ? `0 3px 12px ${m?m.color:C.purple}44`
                    : `0 1px 4px rgba(28,15,60,0.06)`,
                  transform:active?"scale(1.04)":"scale(1)",
                  transition:"all 0.18s",
                }}>
                {m&&<span style={{fontSize:13}}>{m.icon}</span>}{c}
              </button>
            );
          })}
        </div>
      </div>

      {/* ── Posts list ── */}
      <div style={{paddingBottom:96,background:"#F0F2F5",padding:"8px 10px 96px"}}>

        {/* ── Unified feed: ₹250 at top, regular posts, ₹100 interspersed ── */}
        {feedItems.filter(item=>item._type!=="post"||!blockedAuthors.has(item.author)).map(item=>{
          /* ── Business promotion card (₹250 or ₹100) ── */
          if(item._type==="biz"){
            const biz=item;
            const tierColor=biz._tier===250?"#8B5CF6":C.mint;
            return(
              <div key={`biz-${biz.id}`} style={{background:"#fff",borderBottom:`1px solid ${C.border}`,borderLeft:`4px solid ${tierColor}`,paddingLeft:2}}>
                <div style={{padding:"12px 14px",display:"flex",gap:10,alignItems:"flex-start"}}>
                  <div style={{width:42,height:42,borderRadius:12,background:biz.avC,display:"flex",alignItems:"center",justifyContent:"center",color:"#fff",fontWeight:900,fontSize:13,flexShrink:0}}>{biz.av}</div>
                  <div style={{flex:1}}>
                    <div style={{display:"flex",alignItems:"center",gap:5,marginBottom:1}}>
                      <span style={{fontSize:14,fontWeight:900,color:C.text}}>{biz.bizName}</span>
                      {biz.verified&&<span style={{fontSize:9,fontWeight:800,padding:"1px 5px",borderRadius:99,background:"#ECFDF5",color:"#059669"}}>✓ Verified</span>}
                    </div>
                    <div style={{fontSize:10,color:C.muted,marginBottom:5}}>{biz.bizType} · {biz.area}</div>
                    <div style={{fontSize:12,color:C.text,lineHeight:1.5}}>{biz.content}</div>
                    <div style={{marginTop:6,fontSize:11,fontWeight:600,color:tierColor}}>📞 {biz.contact}</div>
                  </div>
                  <button onClick={()=>setPromotionFor(biz.bizName)}
                    style={{fontSize:9,fontWeight:700,padding:"4px 9px",borderRadius:8,background:tierColor,color:"#fff",border:"none",cursor:"pointer",flexShrink:0,alignSelf:"flex-start"}}>Promote</button>
                </div>
              </div>
            );
          }
          /* ── Regular post ── */
          const post=item;
          const m=CAT_META[post.category]||{icon:"📌",color:C.purple};
          const isRemoved=removedPosts.has(post.id);
          const isSharedFromOther=post.sharedFrom&&post.sharedFrom!=="EC Phase 2";
          const isMissingPost=post.category==="Missing Person";
          return(
            <article key={`post-${post.id}`} style={{
              background:"#fff",
              borderRadius:12,
              boxShadow:"0 1px 3px rgba(0,0,0,0.12)",
              marginBottom:10,
              overflow:"hidden",
              ...(isMissingPost?{borderLeft:`4px solid ${C.crimson}`}:{}),
            }}>
              {isRemoved?(
                /* ── Removed by admin overlay ── */
                <div style={{padding:"24px 16px",textAlign:"center",background:"#F9F8FB"}}>
                  <div style={{fontSize:28,marginBottom:6}}>🚫</div>
                  <div style={{fontSize:13,fontWeight:700,color:C.muted}}>Post removed by community admin</div>
                  <div style={{fontSize:11,color:C.muted,marginTop:3}}>This shared post was removed as it was considered off-topic or spam for EC Phase 2.</div>
                </div>
              ):isMissingPost?(
                /* ── MISSING PERSON special card ── */
                <>
                  {/* Urgent crimson header bar */}
                  <div style={{background:C.crimson,padding:"10px 16px",display:"flex",alignItems:"center",justifyContent:"space-between"}}>
                    <div style={{display:"flex",alignItems:"center",gap:8}}>
                      <span style={{fontSize:18}}>🆘</span>
                      <div>
                        <div style={{fontWeight:900,fontSize:13,color:"#fff"}}>
                          {post.missingType==="child"?"MISSING CHILD":"MISSING PERSON"}
                        </div>
                        <div style={{fontSize:10,color:"rgba(255,255,255,0.8)",marginTop:1}}>{post.area} · {post.time}</div>
                      </div>
                    </div>
                    <div style={{display:"flex",gap:4,alignItems:"center"}}>
                      <span style={{fontSize:9,fontWeight:800,padding:"3px 7px",borderRadius:99,background:"rgba(255,255,255,0.22)",color:"#fff"}}>🔊 URGENT TONE</span>
                      <span style={{fontSize:9,fontWeight:800,padding:"3px 7px",borderRadius:99,background:"rgba(255,255,255,0.22)",color:"#fff"}}>247 notified</span>
                    </div>
                  </div>
                  {/* Person details block */}
                  <div style={{padding:"14px 16px"}}>
                    {/* Large name + age */}
                    <div style={{display:"flex",alignItems:"flex-start",gap:12,marginBottom:12}}>
                      <div style={{width:52,height:52,borderRadius:12,background:C.crimsonL,border:`2px dashed ${C.crimson}`,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,fontSize:28}}>
                        {post.missingType==="child"?"👶":"🧑"}
                      </div>
                      <div>
                        <div style={{fontSize:18,fontWeight:900,color:C.crimson}}>{post.missingName}</div>
                        {post.missingAge&&<div style={{fontSize:13,fontWeight:600,color:C.text,marginTop:2}}>Age: {post.missingAge}</div>}
                      </div>
                    </div>
                    {/* Detail rows */}
                    <div style={{display:"flex",flexDirection:"column",gap:7}}>
                      <div style={{display:"flex",gap:8,alignItems:"flex-start"}}>
                        <span style={{fontSize:14,width:22,textAlign:"center",flexShrink:0}}>📍</span>
                        <div>
                          <div style={{fontSize:10,fontWeight:700,color:C.muted,textTransform:"uppercase",letterSpacing:0.5}}>Last Seen</div>
                          <div style={{fontSize:12,fontWeight:600,color:C.text}}>{post.missingLastSeen}</div>
                        </div>
                      </div>
                      {post.missingDesc&&(
                        <div style={{display:"flex",gap:8,alignItems:"flex-start"}}>
                          <span style={{fontSize:14,width:22,textAlign:"center",flexShrink:0}}>👕</span>
                          <div>
                            <div style={{fontSize:10,fontWeight:700,color:C.muted,textTransform:"uppercase",letterSpacing:0.5}}>Description</div>
                            <div style={{fontSize:12,color:C.text}}>{post.missingDesc}</div>
                          </div>
                        </div>
                      )}
                      {post.missingContact&&(
                        <div style={{display:"flex",gap:8,alignItems:"center"}}>
                          <span style={{fontSize:14,width:22,textAlign:"center",flexShrink:0}}>📞</span>
                          <div>
                            <div style={{fontSize:10,fontWeight:700,color:C.muted,textTransform:"uppercase",letterSpacing:0.5}}>Contact</div>
                            <div style={{fontSize:12,fontWeight:700,color:C.crimson}}>{post.missingContact}</div>
                          </div>
                        </div>
                      )}
                    </div>
                    {/* Posted by */}
                    <div style={{marginTop:10,paddingTop:10,borderTop:`1px solid ${C.crimson}22`,display:"flex",alignItems:"center",gap:8}}>
                      <Avatar initials={post.av} color={post.avC} size={28}/>
                      <div style={{fontSize:11,color:C.muted}}>Posted by <span style={{fontWeight:700,color:C.text}}>{post.author}</span> · {post.apartment}</div>
                      <Verified/>
                    </div>
                    {/* Action buttons */}
                    <div style={{marginTop:10,display:"flex",gap:8}}>
                      <button style={{flex:1,padding:"9px",borderRadius:10,background:C.crimson,color:"#fff",fontWeight:900,fontSize:12,border:"none",cursor:"pointer"}}>↗️ Share This Alert</button>
                      <button style={{flex:1,padding:"9px",borderRadius:10,background:C.crimsonL,color:C.crimson,fontWeight:700,fontSize:12,border:`1px solid ${C.crimson}44`,cursor:"pointer"}}>💬 Comment</button>
                    </div>
                    {/* Image thumbnails if any */}
                    {post.images&&post.images.length>0&&(
                      <div style={{marginTop:8,display:"flex",gap:6,flexWrap:"wrap"}}>
                        {post.images.map((img,i)=>(
                          <div key={i} style={{width:64,height:64,borderRadius:10,background:C.crimsonL,border:`1.5px solid ${C.crimson}33`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:22}}>🖼️</div>
                        ))}
                      </div>
                    )}
                  </div>
                  {/* Dispatch confirmation strip */}
                  <div style={{padding:"8px 16px",background:C.crimsonL,borderTop:`1px solid ${C.crimson}22`,display:"flex",flexWrap:"wrap",gap:4}}>
                    <span style={{fontSize:9,fontWeight:800,padding:"2px 7px",borderRadius:99,background:"#fff",color:C.crimson}}>🔔 Push: 247</span>
                    <span style={{fontSize:9,fontWeight:800,padding:"2px 7px",borderRadius:99,background:"#fff",color:"#15803D"}}>📧 Email sent</span>
                    <span style={{fontSize:9,fontWeight:800,padding:"2px 7px",borderRadius:99,background:"#fff",color:"#1D4ED8"}}>💬 SMS sent</span>
                    <span style={{fontSize:9,fontWeight:800,padding:"2px 7px",borderRadius:99,background:"#fff",color:C.crimson}}>🔊 Urgent tone</span>
                  </div>
                  <ReactionBar postId={post.id} baseCounts={POST_RXNS[post.id]||{}} myReaction={reactions[post.id]||null} onReact={handleReact}/>
                </>
              ):(
                /* ── Facebook-style post ── */
                <>
                  {/* ── Author header ── */}
                  <div style={{padding:"14px 16px 10px",display:"flex",alignItems:"center",gap:10}}>
                    {/* Avatar with online dot */}
                    <div style={{position:"relative",flexShrink:0}}>
                      <div style={{
                        width:42,height:42,borderRadius:"50%",
                        background:`linear-gradient(135deg,${post.avC},${post.avC}CC)`,
                        display:"flex",alignItems:"center",justifyContent:"center",
                        color:"#fff",fontWeight:900,fontSize:14,
                        boxShadow:`0 2px 8px ${post.avC}55`,
                      }}>{post.av}</div>
                      <div style={{position:"absolute",bottom:0,right:0,width:12,height:12,borderRadius:"50%",background:"#31A24C",border:"2px solid #fff"}}/>
                    </div>
                    {/* Name + meta */}
                    <div style={{flex:1,minWidth:0}}>
                      <div style={{display:"flex",alignItems:"center",gap:5}}>
                        <span style={{fontWeight:700,fontSize:14,color:C.text}}>{post.author}</span>
                        <Verified/>
                      </div>
                      <div style={{display:"flex",alignItems:"center",gap:5,marginTop:1}}>
                        <span style={{fontSize:11,color:C.muted}}>{post.apartment}</span>
                        <span style={{fontSize:11,color:C.muted}}>·</span>
                        <span style={{fontSize:11,color:C.muted}}>{post.time}</span>
                        <span style={{fontSize:11,color:C.muted}}>·</span>
                        <span style={{fontSize:12}}>🌐</span>
                      </div>
                    </div>
                    {/* ⋮ menu */}
                    <div style={{position:"relative",flexShrink:0}}>
                      <button onClick={e=>{e.stopPropagation();setPostMenu(postMenu===post.id?null:post.id);}}
                        style={{width:36,height:36,borderRadius:"50%",background:postMenu===post.id?"#E4E6EB":"transparent",border:"none",cursor:"pointer",color:C.muted,fontSize:20,display:"flex",alignItems:"center",justifyContent:"center"}}>⋮</button>
                      {postMenu===post.id&&(
                        <div style={{position:"absolute",right:0,top:40,background:"#fff",borderRadius:12,boxShadow:"0 4px 24px rgba(0,0,0,0.18)",zIndex:100,minWidth:200,overflow:"hidden"}} onClick={e=>e.stopPropagation()}>
                          <button style={{width:"100%",padding:"12px 16px",textAlign:"left",border:"none",cursor:"pointer",background:"transparent",fontSize:14,fontWeight:600,color:C.text,display:"flex",alignItems:"center",gap:10}}>🔖 Save Post</button>
                          <button style={{width:"100%",padding:"12px 16px",textAlign:"left",border:"none",cursor:"pointer",background:"transparent",fontSize:14,fontWeight:600,color:C.text,display:"flex",alignItems:"center",gap:10}}>↗️ Share Post</button>
                          <button onClick={()=>{setPostMenu(null);setReportSheet({postId:post.id,author:post.author});}}
                            style={{width:"100%",padding:"12px 16px",textAlign:"left",border:"none",cursor:"pointer",background:"transparent",fontSize:14,fontWeight:600,color:"#F59E0B",display:"flex",alignItems:"center",gap:10}}>⚑ Report Post</button>
                          <button onClick={()=>{setPostMenu(null);setBlockSheet({author:post.author});}}
                            style={{width:"100%",padding:"12px 16px",textAlign:"left",border:"none",cursor:"pointer",background:"#FFF1F2",fontSize:14,fontWeight:700,color:"#F43F5E",display:"flex",alignItems:"center",gap:10}}>🚫 Block {post.author}</button>
                        </div>
                      )}
                    </div>
                  </div>
                  {/* ── Category badge ── */}
                  <div style={{padding:"0 16px 10px",display:"flex",gap:6,flexWrap:"wrap"}}>
                    <span style={{display:"inline-flex",alignItems:"center",gap:4,padding:"4px 12px",borderRadius:99,background:`${m.color}15`,fontSize:12,fontWeight:700,color:m.color}}>
                      {m.icon} {post.category}
                    </span>
                    {isSharedFromOther&&<span style={{display:"inline-flex",alignItems:"center",gap:3,padding:"4px 10px",borderRadius:99,background:C.purpleFg,fontSize:11,fontWeight:700,color:C.purple}}>📡 {post.sharedFrom}</span>}
                    {isSharedFromOther&&<button onClick={()=>adminRemove(post.id)} style={{fontSize:11,fontWeight:700,color:C.coral,background:C.coralL,border:"none",borderRadius:99,padding:"4px 10px",cursor:"pointer"}}>🗑 Remove</button>}
                  </div>
                  {/* ── Post content ── */}
                  <div style={{padding:"0 16px 14px"}}>
                    <p style={{fontSize:15,lineHeight:1.65,color:C.text,margin:0}}>{post.content}</p>
                  </div>
                  {/* ── Reaction summary row ── */}
                  <div style={{padding:"6px 16px",borderTop:`1px solid ${C.border}`,display:"flex",alignItems:"center",justifyContent:"space-between"}}>
                    <div style={{display:"flex",alignItems:"center",gap:4}}>
                      <div style={{display:"flex"}}>
                        <span style={{fontSize:16}}>👍</span>
                        <span style={{fontSize:16,marginLeft:-4}}>❤️</span>
                      </div>
                      <span style={{fontSize:13,color:C.muted}}>{(post.likes||0)+(Math.floor(Math.random()*10))} reactions</span>
                    </div>
                    <div style={{display:"flex",gap:10}}>
                      <span style={{fontSize:13,color:C.muted}}>{post.comments||0} comments</span>
                      <span style={{fontSize:13,color:C.muted}}>·</span>
                      <span style={{fontSize:13,color:C.muted}}>3 shares</span>
                    </div>
                  </div>
                  {/* ── Facebook action buttons ── */}
                  <div style={{display:"flex",borderTop:`1px solid ${C.border}`,padding:"4px 8px"}}>
                    <button style={{flex:1,padding:"8px 0",display:"flex",alignItems:"center",justifyContent:"center",gap:6,border:"none",background:"transparent",cursor:"pointer",borderRadius:8,color:reactions[post.id]?"#1877F2":C.muted,fontWeight:600,fontSize:14}}>
                      <svg width="20" height="20" viewBox="0 0 24 24" fill={reactions[post.id]?"#1877F2":"none"} stroke={reactions[post.id]?"#1877F2":"currentColor"} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3H14z"/><path d="M7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3"/></svg>
                      Like
                    </button>
                    <button style={{flex:1,padding:"8px 0",display:"flex",alignItems:"center",justifyContent:"center",gap:6,border:"none",background:"transparent",cursor:"pointer",borderRadius:8,color:C.muted,fontWeight:600,fontSize:14}}>
                      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>
                      Comment
                    </button>
                    <button style={{flex:1,padding:"8px 0",display:"flex",alignItems:"center",justifyContent:"center",gap:6,border:"none",background:"transparent",cursor:"pointer",borderRadius:8,color:C.muted,fontWeight:600,fontSize:14}}>
                      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="17 1 21 5 17 9"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/><polyline points="7 23 3 19 7 15"/><path d="M21 13v2a4 4 0 0 1-4 4H3"/></svg>
                      Share
                    </button>
                  </div>
                </>
              )}
            </article>
          );
        })}
      </div>
    </div>
  );
}

function EventsScreen(){
  const [sub,setSub]=useState("events");
  const [rsvp,setRsvp]=useState({});
  const [lf,setLf]=useState("All");
  const [creating,setCreating]=useState(false);
  const filtered=lf==="All"?LISTINGS:LISTINGS.filter(l=>l.type===lf);
  if(creating) return <EventCreateScreen onBack={()=>setCreating(false)}/>;
  return(
    <div>
      {/* Events tab bar */}
      <div style={{padding:"14px 14px 10px",display:"flex",gap:8}}>
        {[["events","📅","Events"],["listings","🛍️","Market"]].map(([id,ic,label])=>(
          <button key={id} onClick={()=>setSub(id)}
            style={{
              flex:1,padding:"11px 0",borderRadius:16,fontSize:13,fontWeight:900,
              border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:6,
              background:sub===id?G.tabEvents:"#fff",
              color:sub===id?"#fff":C.muted,
              boxShadow:sub===id?"0 4px 16px rgba(79,70,229,0.35)":C.shadowSm,
              transition:"all 0.2s",
            }}><span style={{fontSize:16}}>{ic}</span>{label}</button>
        ))}
      </div>
      {sub==="events"&&(
        <div className="px-3 pb-24 space-y-3">
          <button onClick={()=>setCreating(true)} className="w-full py-3 rounded-2xl text-sm font-black text-white" style={{background:`linear-gradient(135deg,${C.purple},${C.purpleL})`}}>+ Host a Community Event</button>
          {/* ── NEXT UP spotlight ── */}
          {EVENTS.length>0&&(
            <div style={{borderRadius:22,overflow:"hidden",marginBottom:4,background:`linear-gradient(135deg,${EVENTS[0].col},${EVENTS[0].col}CC)`,boxShadow:`0 6px 24px ${EVENTS[0].col}44`}}>
              <div style={{padding:"6px 14px",display:"flex",alignItems:"center",gap:6,borderBottom:"1px solid rgba(255,255,255,0.18)"}}>
                <span style={{fontSize:10,fontWeight:900,color:"rgba(255,255,255,0.9)",letterSpacing:"0.08em"}}>⭐ NEXT UP</span>
              </div>
              <div style={{padding:"16px 16px 6px",display:"flex",gap:14,alignItems:"flex-start"}}>
                {/* Date badge */}
                <div style={{flexShrink:0,width:52,borderRadius:14,overflow:"hidden",background:"rgba(255,255,255,0.22)",border:"1.5px solid rgba(255,255,255,0.35)",textAlign:"center"}}>
                  <div style={{background:"rgba(255,255,255,0.25)",padding:"5px 0",fontSize:9,fontWeight:900,color:"rgba(255,255,255,0.9)",letterSpacing:"0.06em"}}>{EVENTS[0].date.split(" ")[1]||"MAR"}</div>
                  <div style={{padding:"6px 0",fontSize:24,fontWeight:900,color:"#fff",lineHeight:1}}>{EVENTS[0].date.split(" ")[0]||"15"}</div>
                </div>
                <div style={{flex:1,minWidth:0}}>
                  <div style={{fontSize:17,fontWeight:900,color:"#fff",lineHeight:1.2,marginBottom:5}}>{EVENTS[0].title}</div>
                  <div style={{display:"flex",flexWrap:"wrap",gap:6,marginBottom:8}}>
                    <span style={{fontSize:10,fontWeight:800,padding:"3px 9px",borderRadius:99,background:"rgba(255,255,255,0.22)",color:"#fff"}}>{EVENTS[0].icon} {EVENTS[0].category}</span>
                    <span style={{fontSize:10,fontWeight:700,padding:"3px 9px",borderRadius:99,background:"rgba(255,255,255,0.22)",color:"#fff"}}>⏰ {EVENTS[0].time}</span>
                  </div>
                  <div style={{fontSize:11,color:"rgba(255,255,255,0.8)",display:"flex",alignItems:"center",gap:5}}>
                    <span>📍</span><span style={{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{EVENTS[0].location}</span>
                  </div>
                </div>
                <div style={{textAlign:"center",flexShrink:0}}>
                  <div style={{fontSize:20,fontWeight:900,color:"#fff"}}>{EVENTS[0].attendees+(rsvp[EVENTS[0].id]?1:0)}</div>
                  <div style={{fontSize:9,color:"rgba(255,255,255,0.75)",fontWeight:600}}>GOING</div>
                </div>
              </div>
              <div style={{padding:"10px 14px 14px"}}>
                <button onClick={()=>setRsvp(r=>({...r,[EVENTS[0].id]:!r[EVENTS[0].id]}))}
                  style={{width:"100%",padding:"11px",borderRadius:14,fontSize:13,fontWeight:900,border:"none",cursor:"pointer",background:rsvp[EVENTS[0].id]?"rgba(255,255,255,0.25)":"rgba(255,255,255,0.18)",color:"#fff",backdropFilter:"blur(4px)",transition:"all 0.2s"}}>
                  {rsvp[EVENTS[0].id]?"✅ You're Going! · Tap to cancel":"→ RSVP — I'll be there"}
                </button>
              </div>
            </div>
          )}
          {/* ── Upcoming section label ── */}
          {EVENTS.length>1&&<div style={{display:"flex",alignItems:"center",gap:10,margin:"8px 16px 0"}}>
            <div style={{flex:1,height:1,background:C.border}}/>
            <span style={{fontSize:10,fontWeight:900,color:C.muted,letterSpacing:"0.06em"}}>ALL EVENTS</span>
            <div style={{flex:1,height:1,background:C.border}}/>
          </div>}
          {EVENTS.map((ev,evIdx)=>(
            <div key={ev.id} style={{background:"#fff",borderBottom:`1px solid ${C.border}`,padding:"16px",display:"flex",gap:14,alignItems:"flex-start"}}>
              {/* Date circle */}
              <div style={{flexShrink:0,width:52,display:"flex",flexDirection:"column",alignItems:"center",gap:6}}>
                <div style={{width:52,height:52,borderRadius:"50%",background:`${ev.col}12`,border:`2.5px solid ${ev.col}`,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"}}>
                  <div style={{fontSize:20,fontWeight:900,color:ev.col,lineHeight:1}}>{ev.date.split(" ")[0]||"15"}</div>
                  <div style={{fontSize:9,fontWeight:800,color:ev.col,textTransform:"uppercase",letterSpacing:"0.05em"}}>{ev.date.split(" ")[1]||"MAR"}</div>
                </div>
                <div style={{fontSize:20}}>{ev.icon}</div>
              </div>
              {/* Event content */}
              <div style={{flex:1,minWidth:0}}>
                <div style={{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:8,marginBottom:5}}>
                  <div style={{fontSize:15,fontWeight:900,color:C.text,lineHeight:1.3}}>{ev.title}</div>
                  <div style={{textAlign:"center",flexShrink:0,minWidth:44}}>
                    <div style={{fontSize:17,fontWeight:900,color:ev.col}}>{ev.attendees+(rsvp[ev.id]?1:0)}</div>
                    <div style={{fontSize:9,color:C.muted,fontWeight:700,letterSpacing:"0.04em"}}>GOING</div>
                  </div>
                </div>
                <span style={{display:"inline-flex",alignItems:"center",gap:3,padding:"3px 10px",borderRadius:99,fontSize:10,fontWeight:800,background:`${ev.col}12`,color:ev.col,marginBottom:8}}>{ev.category}</span>
                <div style={{display:"flex",flexDirection:"column",gap:3,marginBottom:12}}>
                  <div style={{display:"flex",alignItems:"center",gap:6,fontSize:12,color:C.muted}}>
                    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
                    <span>{ev.time}</span>
                  </div>
                  <div style={{display:"flex",alignItems:"center",gap:6,fontSize:12,color:C.muted,overflow:"hidden"}}>
                    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{flexShrink:0}}><path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/><circle cx="12" cy="10" r="3"/></svg>
                    <span style={{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}}>{ev.location}</span>
                  </div>
                </div>
                <div style={{display:"flex",gap:8}}>
                  <button onClick={()=>setRsvp(r=>({...r,[ev.id]:!r[ev.id]}))}
                    style={{padding:"8px 20px",borderRadius:99,fontSize:13,fontWeight:900,border:`2px solid ${rsvp[ev.id]?ev.col:C.border}`,cursor:"pointer",background:rsvp[ev.id]?ev.col:"transparent",color:rsvp[ev.id]?"#fff":C.text,transition:"all 0.2s",boxShadow:rsvp[ev.id]?`0 4px 14px ${ev.col}44`:"none"}}>
                    {rsvp[ev.id]?"✅ Going":"RSVP →"}
                  </button>
                  <button style={{padding:"8px 16px",borderRadius:99,fontSize:12,fontWeight:700,border:`1.5px solid ${C.border}`,cursor:"pointer",background:"transparent",color:C.muted}}>
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{display:"inline",verticalAlign:"middle",marginRight:4}}><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/><line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/></svg>
                    Share
                  </button>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
      {sub==="listings"&&(
        <div className="px-3 pb-24 space-y-3">
          <button className="w-full py-3 rounded-2xl text-sm font-black text-white" style={{background:`linear-gradient(135deg,${C.mint},#00967E)`}}>+ Post a Listing</button>
          <div className="flex gap-2 overflow-x-auto pb-1">
            {["All","For Sale","Free","For Rent","Service"].map(f=>(
              <button key={f} onClick={()=>setLf(f)} className="px-3 py-1.5 rounded-full text-xs font-bold whitespace-nowrap border-2 transition-all"
                style={lf===f?{background:C.mint,color:"#fff",borderColor:C.mint}:{background:"#fff",color:C.muted,borderColor:C.border}}>{f}</button>
            ))}
          </div>
          <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10}}>
          {filtered.map(item=>(
            <div key={item.id} style={{borderRadius:18,background:"#fff",border:`1.5px solid ${C.border}`,overflow:"hidden",display:"flex",flexDirection:"column"}}>
              {/* Icon area */}
              <div style={{height:80,background:`linear-gradient(135deg,${item.col}22,${item.col}08)`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:38,borderBottom:`1px solid ${item.col}18`}}>{item.icon}</div>
              <div style={{padding:"10px 10px 12px",flex:1,display:"flex",flexDirection:"column",gap:4}}>
                <span style={{fontSize:9,fontWeight:800,padding:"2px 7px",borderRadius:99,background:item.col+"20",color:item.col,alignSelf:"flex-start"}}>{item.type}</span>
                <div style={{fontSize:12,fontWeight:900,color:"#18103A",lineHeight:1.3}}>{item.title}</div>
                <div style={{fontSize:10,color:"#7C7290",marginBottom:2}}>{item.seller}</div>
                <div style={{fontSize:13,fontWeight:900,color:"#5C2D91",marginBottom:6}}>{item.price}</div>
                <button style={{width:"100%",padding:"8px",borderRadius:11,fontSize:11,fontWeight:900,background:"#F3EBFF",color:"#5C2D91",border:"none",cursor:"pointer",marginTop:"auto"}}>💬 Message</button>
              </div>
            </div>
          ))}
          </div>
        </div>
      )}
    </div>
  );
}

function MapScreen(){
  const [ap,setAp]=useState(null);
  const [showParks, setShowParks] = useState(false);
  const PINS=[
    // Areas
    {x:42,y:30,label:"EC Phase 1",  c:C.purple,  t:"area"},
    {x:60,y:47,label:"EC Phase 2",  c:C.purple,  t:"area"},
    {x:28,y:57,label:"Hebbagodi",   c:"#6B7FF0", t:"area"},
    {x:70,y:62,label:"Bommasandra", c:"#6B7FF0", t:"area"},
    {x:50,y:72,label:"Neeladri Nagar",c:C.mint,  t:"area"},
    {x:76,y:36,label:"Kudlu",       c:C.mint,    t:"area"},
    // Alerts / Events / Shops
    {x:36,y:42,label:"Alert",       c:C.coral,   t:"alert"},
    {x:55,y:32,label:"Holi Event",  c:C.marigold,t:"event"},
    {x:45,y:60,label:"Sri Lakshmi", c:C.mint,    t:"shop"},
    {x:63,y:53,label:"Veggie Mart", c:C.mint,    t:"shop"},
    // Parks & Lakes (from PARKS data)
    ...PARKS.map(p=>({x:p.mapX, y:p.mapY, label:p.name, c:"#16A34A", t:"park"})),
    // Supermarkets & Grocery (from SUPERMARKETS data)
    ...SUPERMARKETS.map(s=>({x:s.mapX, y:s.mapY, label:s.name, c:"#EA580C", t:"grocery"})),
    // Schools & Daycare (from SCHOOLS data)
    ...SCHOOLS.map(s=>({x:s.mapX, y:s.mapY, label:s.name, c:"#2563EB", t:"school"})),
    // Hospitals (from HOSPITALS data)
    ...HOSPITALS.map(h=>({x:h.mapX, y:h.mapY, label:h.name, c:"#DC2626", t:"hospital"})),
    // Petrol Pumps (from PETROL_PUMPS data)
    ...PETROL_PUMPS.map(p=>({x:p.mapX, y:p.mapY, label:p.name, c:"#D97706", t:"petrol"})),
    // Hotels (from HOTELS data)
    ...HOTELS.map(h=>({x:h.mapX, y:h.mapY, label:h.name, c:"#7C3AED", t:"hotel"})),
    // Temples & Worship (from TEMPLES data)
    ...TEMPLES.map(t=>({x:t.mapX, y:t.mapY, label:t.name, c:"#B45309", t:"temple"})),
    // Cinemas (from CINEMAS data)
    ...CINEMAS.map(c=>({x:c.mapX, y:c.mapY, label:c.name, c:"#0891B2", t:"cinema"})),
    // ATMs (from ATMS data)
    ...ATMS.map(a=>({x:a.mapX, y:a.mapY, label:a.name, c:"#059669", t:"atm"})),
    // Restaurants (from RESTAURANTS data)
    ...RESTAURANTS.map(r=>({x:r.mapX, y:r.mapY, label:r.name, c:"#DC2626", t:"restaurant"})),
  ];
  const PI={area:"📍",alert:"⚠️",event:"🎉",shop:"🛒",park:"🌳",grocery:"🛒",school:"🏫",hospital:"🏥",petrol:"⛽",hotel:"🏨",temple:"🛕",cinema:"🎬",atm:"🏧",restaurant:"🍽️"};
  return(
    <div className="p-3 pb-24">
      <div className="flex items-center justify-between mb-3">
        <h2 className="font-black text-lg" style={{color:C.text}}>Neighbourhood Map</h2>
        <span className="text-xs font-bold px-3 py-1 rounded-full" style={{background:C.purpleFg,color:C.purple}}>EC · Bangalore</span>
      </div>
      {/* Map filter toggles */}
      <div style={{display:"flex",gap:6,marginBottom:10,flexWrap:"wrap"}}>
        {[
          {label:"All",              t:null,      c:C.purple},
          {label:"🌳 Parks & Lakes", t:"park",    c:"#16A34A"},
          {label:"🛒 Grocery",       t:"grocery", c:"#EA580C"},
          {label:"🏫 Schools",       t:"school",   c:"#2563EB"},
          {label:"🏥 Hospitals",     t:"hospital", c:"#DC2626"},
          {label:"⛽ Petrol",        t:"petrol",   c:"#D97706"},
          {label:"🏨 Hotels",        t:"hotel",    c:"#7C3AED"},
          {label:"🛕 Temples",       t:"temple",   c:"#B45309"},
          {label:"🎬 Cinemas",       t:"cinema",   c:"#0891B2"},
          {label:"🏧 ATMs",          t:"atm",      c:"#059669"},
          {label:"⚠️ Alerts",        t:"alert",    c:C.coral},
          {label:"🍽️ Food",          t:"restaurant", c:"#DC2626"},
          {label:"🎉 Events",        t:"event",    c:C.marigold},
          {label:"🏪 Shops",         t:"shop",     c:C.mint},
        ].map(f=>{
          const active = showParks===f.t;
          return(
            <button key={f.label} onClick={()=>setShowParks(active?false:f.t)}
              style={{padding:"5px 12px",borderRadius:99,fontSize:11,fontWeight:700,cursor:"pointer",border:`1.5px solid ${active?f.c:C.border}`,background:active?`${f.c}18`:"#fff",color:active?f.c:C.muted}}>
              {f.label}
            </button>
          );
        })}
      </div>

      <div className="rounded-3xl overflow-hidden relative mb-2" style={{height:300,background:"linear-gradient(145deg,#e8eaff,#f3e8ff,#e0f7f4)"}}>
        <svg className="absolute inset-0 w-full h-full" style={{opacity:0.45}}>
          <line x1="5%" y1="50%" x2="95%" y2="50%" stroke="#c8b6e8" strokeWidth="7"/>
          <line x1="50%" y1="5%" x2="50%" y2="95%" stroke="#c8b6e8" strokeWidth="7"/>
          <line x1="15%" y1="15%" x2="85%" y2="85%" stroke="#a8d8cf" strokeWidth="4"/>
          <line x1="72%" y1="10%" x2="28%" y2="78%" stroke="#a8d8cf" strokeWidth="4"/>
          <text x="52%" y="46%" fill="#9b72d4" fontSize="8" fontWeight="bold">NICE Road</text>
          <text x="8%" y="52%" fill="#9b72d4" fontSize="7">Hosur Rd</text>
          <text x="52%" y="18%" fill="#9b72d4" fontSize="7">Sarjapur Rd</text>
        </svg>
        {PINS.filter(p=> showParks===false || showParks===null ? true : p.t===showParks).map((p,i)=>(
          <button key={i} onClick={()=>setAp(ap===i?null:i)} className="absolute flex flex-col items-center transition-transform hover:scale-110"
            style={{left:`${p.x}%`,top:`${p.y}%`,transform:"translate(-50%,-100%)"}}>
            <div className="w-9 h-9 rounded-2xl flex items-center justify-center text-base shadow-lg border-2 border-white" style={{background:p.c}}>{PI[p.t]}</div>
            {(ap===i||p.t==="area")&&<div className="mt-1 px-2 py-0.5 rounded-xl text-xs font-black shadow whitespace-nowrap" style={{background:"#fff",color:p.c}}>{p.label}</div>}
          </button>
        ))}
        <div className="absolute" style={{left:"42%",top:"30%",transform:"translate(-50%,-50%)"}}>
          <div className="w-4 h-4 rounded-full border-2 border-white shadow animate-pulse" style={{background:"#3B82F6"}}/>
        </div>
        <div className="absolute bottom-3 right-3 rounded-xl px-3 py-1.5 text-xs font-semibold flex items-center gap-1.5 shadow" style={{background:"rgba(255,255,255,0.92)",color:C.muted}}>
          <span className="w-2 h-2 rounded-full inline-block" style={{background:"#3B82F6"}}/>You're here
        </div>
      </div>
      {/* Map legend */}
      <div style={{display:"flex",gap:10,flexWrap:"wrap",marginBottom:14,padding:"6px 2px"}}>
        {[["📍","Areas","#5C2D91"],["🌳","Parks","#16A34A"],["🛒","Grocery","#EA580C"],["🏫","Schools","#2563EB"],["🏥","Hospitals","#DC2626"],["⛽","Petrol","#D97706"],["🏨","Hotels","#7C3AED"],["🛕","Temples","#B45309"],["🎬","Cinemas","#0891B2"],["🏧","ATMs","#059669"],["🍽️","Food","#DC2626"],["⚠️","Alerts","#FF6B7A"],["🎉","Events","#FFB347"]].map(([ico,lbl,col])=>(
          <span key={lbl} style={{display:"flex",alignItems:"center",gap:4,fontSize:11,color:col,fontWeight:700}}>
            <span>{ico}</span>{lbl}
          </span>
        ))}
      </div>
      <h3 className="font-black text-sm mb-2" style={{color:C.text}}>📍 All Covered Areas</h3>
      <div className="grid grid-cols-2 gap-2 mb-5">
        {AREAS_LIST.map(a=>(
          <div key={a.name} className="rounded-xl p-3 flex items-center gap-2" style={{background:"#fff",border:`1.5px solid ${C.border}`}}>
            <div className="w-2 h-2 rounded-full flex-shrink-0" style={{background:C.purple}}/>
            <div className="min-w-0">
              <div className="text-xs font-bold truncate" style={{color:C.text}}>{a.name}</div>
              <div className="text-xs" style={{color:C.muted}}>PIN {a.pin}</div>
            </div>
          </div>
        ))}
      </div>
      {/* ── Nearby Areas (within 10 km) ── */}
      <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:10}}>
        <h3 className="font-black text-sm" style={{color:C.text}}>🗺 Nearby Areas</h3>
        <span style={{fontSize:11,fontWeight:700,padding:"3px 10px",borderRadius:99,background:C.purpleFg,color:C.purple}}>Within 10 km</span>
      </div>
      <div style={{display:"flex",flexDirection:"column",gap:7,marginBottom:20}}>
        {NEARBY_LOCALITIES.map(a=>(
          <div key={a.name} style={{borderRadius:12,background:"#fff",border:`1.5px solid ${C.border}`,padding:"10px 12px",display:"flex",alignItems:"center",gap:10}}>
            {/* Direction compass badge */}
            <div style={{width:36,height:36,borderRadius:10,background:`${a.color}18`,border:`1.5px solid ${a.color}33`,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",flexShrink:0}}>
              <span style={{fontSize:9,fontWeight:900,color:a.color,letterSpacing:"0.05em"}}>{a.dir}</span>
              <span style={{fontSize:8,color:a.color,fontWeight:700}}>{a.dist}</span>
            </div>
            <div style={{flex:1,minWidth:0}}>
              <div style={{fontWeight:800,fontSize:13,color:"#1F2937"}}>{a.name}</div>
              <div style={{fontSize:11,color:"#6B7280",marginTop:1,lineHeight:1.4}}>{a.note}</div>
            </div>
            <div style={{padding:"3px 10px",borderRadius:99,background:`${a.color}14`,flexShrink:0}}>
              <span style={{fontSize:11,fontWeight:700,color:a.color}}>{a.dist}</span>
            </div>
          </div>
        ))}
      </div>

      <h3 className="font-black text-sm mb-2" style={{color:C.text}}>📁 Local Directory</h3>
      <div className="space-y-2 mb-5">
        {DIRECTORY.map(([ic,lb,n])=>(
          <button key={lb} className="w-full rounded-xl p-3 flex items-center justify-between" style={{background:"#fff",border:`1.5px solid ${C.border}`}}>
            <div className="flex items-center gap-3"><span className="text-xl">{ic}</span><span className="text-sm font-bold" style={{color:C.text}}>{lb}</span></div>
            <div className="flex items-center gap-1.5">
              <span className="text-xs font-black px-2 py-0.5 rounded-full" style={{background:C.purpleFg,color:C.purple}}>{n}</span>
              <span className="font-black" style={{color:C.muted}}>›</span>
            </div>
          </button>
        ))}
      </div>

      {/* ── Parks & Recreation ── */}
      <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:10}}>
        <h3 className="font-black text-sm" style={{color:C.text}}>🌳 Parks & Recreation</h3>
        <span style={{fontSize:11,fontWeight:700,padding:"3px 10px",borderRadius:99,background:"#DCFCE7",color:"#16A34A"}}>{PARKS.length} spots</span>
      </div>
      <div style={{display:"flex",flexDirection:"column",gap:9,marginBottom:20}}>
        {PARKS.map(park=>(
          <div key={park.name} style={{borderRadius:14,background:"#fff",border:"1.5px solid #BBF7D0",overflow:"hidden",display:"flex"}}>
            <div style={{width:5,flexShrink:0,background: park.type==="Lake"?"#0EA5E9": park.type.includes("Cycling")?"#F59E0B": park.type.includes("Heritage")?"#A855F7":"#16A34A"}}/>
            <div style={{flex:1,padding:"11px 12px"}}>
              <div style={{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:6,marginBottom:4}}>
                <div style={{display:"flex",alignItems:"center",gap:7}}>
                  <span style={{fontSize:20}}>{park.icon}</span>
                  <div>
                    <div style={{fontWeight:800,fontSize:13,color:"#1F2937",lineHeight:1.2}}>{park.name}</div>
                    <div style={{fontSize:11,color:"#6B7280",marginTop:1}}>{park.area}</div>
                  </div>
                </div>
                <span style={{flexShrink:0,fontSize:10,fontWeight:700,padding:"2px 8px",borderRadius:99,
                  background: park.type==="Lake"?"#E0F2FE": park.type.includes("Cycling")?"#FEF3C7": park.type.includes("Heritage")?"#F3E8FF":"#DCFCE7",
                  color:       park.type==="Lake"?"#0369A1": park.type.includes("Cycling")?"#B45309": park.type.includes("Heritage")?"#7E22CE":"#15803D",
                  whiteSpace:"nowrap"}}>
                  {park.type}
                </span>
              </div>
              <div style={{fontSize:12,color:"#4B5563",lineHeight:1.5,marginBottom:5}}>{park.desc}</div>
              <div style={{display:"flex",alignItems:"center",gap:5}}>
                <span style={{fontSize:11}}>🕐</span>
                <span style={{fontSize:11,fontWeight:600,color:"#6B7280"}}>{park.timings}</span>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* ── Grocery & Supermarkets ── */}
      <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:10}}>
        <h3 className="font-black text-sm" style={{color:C.text}}>🛒 Grocery & Supermarkets</h3>
        <span style={{fontSize:11,fontWeight:700,padding:"3px 10px",borderRadius:99,background:"#FFF7ED",color:"#EA580C"}}>{SUPERMARKETS.length} stores</span>
      </div>
      <div style={{display:"flex",flexDirection:"column",gap:9}}>
        {SUPERMARKETS.map(store=>{
          const typeColor = store.type==="Hypermarket"?"#7C3AED": store.type==="Fresh Produce"?"#16A34A": store.type==="Kirana / Daily Needs"?"#0369A1":"#EA580C";
          const typeBg    = store.type==="Hypermarket"?"#F3E8FF": store.type==="Fresh Produce"?"#DCFCE7": store.type==="Kirana / Daily Needs"?"#E0F2FE":"#FFF7ED";
          const barColor  = store.type==="Hypermarket"?"#7C3AED": store.type==="Fresh Produce"?"#16A34A": store.type==="Kirana / Daily Needs"?"#0369A1":"#EA580C";
          return(
            <div key={store.name} style={{borderRadius:14,background:"#fff",border:"1.5px solid #FED7AA",overflow:"hidden",display:"flex"}}>
              <div style={{width:5,flexShrink:0,background:barColor}}/>
              <div style={{flex:1,padding:"11px 12px"}}>
                <div style={{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:6,marginBottom:4}}>
                  <div style={{display:"flex",alignItems:"center",gap:7}}>
                    <span style={{fontSize:20}}>{store.icon}</span>
                    <div>
                      <div style={{fontWeight:800,fontSize:13,color:"#1F2937",lineHeight:1.2}}>{store.name}</div>
                      <div style={{fontSize:11,color:"#6B7280",marginTop:1}}>{store.area}</div>
                    </div>
                  </div>
                  <span style={{flexShrink:0,fontSize:10,fontWeight:700,padding:"2px 8px",borderRadius:99,background:typeBg,color:typeColor,whiteSpace:"nowrap"}}>
                    {store.type}
                  </span>
                </div>
                <div style={{fontSize:12,color:"#4B5563",lineHeight:1.5,marginBottom:5}}>{store.desc}</div>
                <div style={{display:"flex",alignItems:"center",gap:5}}>
                  <span style={{fontSize:11}}>🕐</span>
                  <span style={{fontSize:11,fontWeight:600,color:"#6B7280"}}>{store.timings}</span>
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {/* ── Schools & Daycare ── */}
      <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",margin:"18px 0 10px"}}>
        <h3 className="font-black text-sm" style={{color:C.text}}>🏫 Schools & Daycare</h3>
        <span style={{fontSize:11,fontWeight:700,padding:"3px 10px",borderRadius:99,background:"#EFF6FF",color:"#2563EB"}}>{SCHOOLS.length} listed</span>
      </div>
      <div style={{display:"flex",flexDirection:"column",gap:9}}>
        {SCHOOLS.map(school=>{
          const isGovt   = school.type.includes("Govt");
          const isDaycare= school.type.includes("Preschool")||school.type.includes("Daycare");
          const barColor = isGovt?"#7C3AED": isDaycare?"#EC4899":"#2563EB";
          const badgeBg  = isGovt?"#F3E8FF": isDaycare?"#FCE7F3":"#EFF6FF";
          const badgeCol = isGovt?"#7C3AED": isDaycare?"#9D174D":"#1D4ED8";
          return(
            <div key={school.name} style={{borderRadius:14,background:"#fff",border:"1.5px solid #BFDBFE",overflow:"hidden",display:"flex"}}>
              <div style={{width:5,flexShrink:0,background:barColor}}/>
              <div style={{flex:1,padding:"11px 12px"}}>
                <div style={{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:6,marginBottom:4}}>
                  <div style={{display:"flex",alignItems:"center",gap:7}}>
                    <span style={{fontSize:20}}>{school.icon}</span>
                    <div>
                      <div style={{fontWeight:800,fontSize:13,color:"#1F2937",lineHeight:1.2}}>{school.name}</div>
                      <div style={{fontSize:11,color:"#6B7280",marginTop:1}}>{school.area}</div>
                    </div>
                  </div>
                  <span style={{flexShrink:0,fontSize:10,fontWeight:700,padding:"2px 7px",borderRadius:99,background:badgeBg,color:badgeCol,whiteSpace:"nowrap",maxWidth:100,textAlign:"right",lineHeight:1.3}}>
                    {school.type}
                  </span>
                </div>
                <div style={{fontSize:12,color:"#4B5563",lineHeight:1.5,marginBottom:5}}>{school.desc}</div>
                <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",flexWrap:"wrap",gap:4}}>
                  <div style={{display:"flex",alignItems:"center",gap:5}}>
                    <span style={{fontSize:11}}>🕐</span>
                    <span style={{fontSize:11,fontWeight:600,color:"#6B7280"}}>{school.timings}</span>
                  </div>
                  {school.phone&&(
                    <a href={`tel:${school.phone}`} style={{fontSize:11,fontWeight:700,color:"#2563EB",textDecoration:"none",display:"flex",alignItems:"center",gap:3}}>
                      📞 {school.phone}
                    </a>
                  )}
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {/* ── Hospitals & Clinics ── */}
      <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",margin:"18px 0 10px"}}>
        <h3 className="font-black text-sm" style={{color:C.text}}>🏥 Hospitals & Clinics</h3>
        <span style={{fontSize:11,fontWeight:700,padding:"3px 10px",borderRadius:99,background:"#FEF2F2",color:"#DC2626"}}>{HOSPITALS.length} listed</span>
      </div>
      <div style={{display:"flex",flexDirection:"column",gap:9,marginBottom:4}}>
        {HOSPITALS.map(h=>(
          <div key={h.name} style={{borderRadius:14,background:"#fff",border:"1.5px solid #FECACA",overflow:"hidden",display:"flex"}}>
            <div style={{width:5,flexShrink:0,background:h.type.includes("Govt")?"#7C3AED":h.type.includes("Clinic")?"#059669":"#DC2626"}}/>
            <div style={{flex:1,padding:"11px 12px"}}>
              <div style={{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:6,marginBottom:4}}>
                <div style={{display:"flex",alignItems:"center",gap:7}}>
                  <span style={{fontSize:20}}>{h.icon}</span>
                  <div>
                    <div style={{fontWeight:800,fontSize:13,color:"#1F2937",lineHeight:1.2}}>{h.name}</div>
                    <div style={{fontSize:11,color:"#6B7280",marginTop:1}}>{h.area}</div>
                  </div>
                </div>
                <span style={{flexShrink:0,fontSize:10,fontWeight:700,padding:"2px 7px",borderRadius:99,background:h.type.includes("Govt")?"#F3E8FF":h.type.includes("Clinic")?"#DCFCE7":"#FEF2F2",color:h.type.includes("Govt")?"#7C3AED":h.type.includes("Clinic")?"#059669":"#DC2626",whiteSpace:"nowrap"}}>{h.type}</span>
              </div>
              <div style={{fontSize:12,color:"#4B5563",lineHeight:1.5,marginBottom:5}}>{h.desc}</div>
              <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",flexWrap:"wrap",gap:4}}>
                <div style={{display:"flex",alignItems:"center",gap:5}}><span style={{fontSize:11}}>🕐</span><span style={{fontSize:11,fontWeight:600,color:"#6B7280"}}>{h.timings}</span></div>
                {h.phone&&<a href={`tel:${h.phone}`} style={{fontSize:11,fontWeight:700,color:"#DC2626",textDecoration:"none"}}>📞 {h.phone}</a>}
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* ── Petrol Pumps ── */}
      <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",margin:"18px 0 10px"}}>
        <h3 className="font-black text-sm" style={{color:C.text}}>⛽ Petrol Pumps</h3>
        <span style={{fontSize:11,fontWeight:700,padding:"3px 10px",borderRadius:99,background:"#FFFBEB",color:"#D97706"}}>{PETROL_PUMPS.length} stations</span>
      </div>
      <div style={{display:"flex",flexDirection:"column",gap:9,marginBottom:4}}>
        {PETROL_PUMPS.map(p=>(
          <div key={p.name} style={{borderRadius:14,background:"#fff",border:"1.5px solid #FDE68A",overflow:"hidden",display:"flex"}}>
            <div style={{width:5,flexShrink:0,background:"#D97706"}}/>
            <div style={{flex:1,padding:"11px 12px"}}>
              <div style={{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:6,marginBottom:4}}>
                <div style={{display:"flex",alignItems:"center",gap:7}}>
                  <span style={{fontSize:20}}>{p.icon}</span>
                  <div>
                    <div style={{fontWeight:800,fontSize:13,color:"#1F2937",lineHeight:1.2}}>{p.name}</div>
                    <div style={{fontSize:11,color:"#6B7280",marginTop:1}}>{p.area}</div>
                  </div>
                </div>
                <span style={{flexShrink:0,fontSize:10,fontWeight:700,padding:"2px 7px",borderRadius:99,background:"#FFFBEB",color:"#B45309",whiteSpace:"nowrap"}}>{p.type}</span>
              </div>
              <div style={{fontSize:12,color:"#4B5563",lineHeight:1.5,marginBottom:5}}>{p.desc}</div>
              <div style={{display:"flex",alignItems:"center",gap:5}}><span style={{fontSize:11}}>🕐</span><span style={{fontSize:11,fontWeight:600,color:"#6B7280"}}>{p.timings}</span></div>
            </div>
          </div>
        ))}
      </div>

      {/* ── Hotels & Stay ── */}
      <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",margin:"18px 0 10px"}}>
        <h3 className="font-black text-sm" style={{color:C.text}}>🏨 Hotels & Stay</h3>
        <span style={{fontSize:11,fontWeight:700,padding:"3px 10px",borderRadius:99,background:"#F3E8FF",color:"#7C3AED"}}>{HOTELS.length} options</span>
      </div>
      <div style={{display:"flex",flexDirection:"column",gap:9,marginBottom:4}}>
        {HOTELS.map(h=>(
          <div key={h.name} style={{borderRadius:14,background:"#fff",border:"1.5px solid #DDD6FE",overflow:"hidden",display:"flex"}}>
            <div style={{width:5,flexShrink:0,background:h.type==="4-Star"?"#F59E0B":h.type==="3-Star"?"#7C3AED":"#6B7280"}}/>
            <div style={{flex:1,padding:"11px 12px"}}>
              <div style={{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:6,marginBottom:4}}>
                <div style={{display:"flex",alignItems:"center",gap:7}}>
                  <span style={{fontSize:20}}>{h.icon}</span>
                  <div>
                    <div style={{fontWeight:800,fontSize:13,color:"#1F2937",lineHeight:1.2}}>{h.name}</div>
                    <div style={{fontSize:11,color:"#6B7280",marginTop:1}}>{h.area}</div>
                  </div>
                </div>
                <span style={{flexShrink:0,fontSize:10,fontWeight:700,padding:"2px 7px",borderRadius:99,background:h.type==="4-Star"?"#FEF3C7":h.type==="3-Star"?"#F3E8FF":"#F3F4F6",color:h.type==="4-Star"?"#B45309":h.type==="3-Star"?"#7C3AED":"#374151",whiteSpace:"nowrap"}}>{h.type}</span>
              </div>
              <div style={{fontSize:12,color:"#4B5563",lineHeight:1.5,marginBottom:5}}>{h.desc}</div>
              <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",flexWrap:"wrap",gap:4}}>
                <div style={{display:"flex",alignItems:"center",gap:5}}><span style={{fontSize:11}}>🕐</span><span style={{fontSize:11,fontWeight:600,color:"#6B7280"}}>{h.timings}</span></div>
                {h.phone&&<a href={`tel:${h.phone}`} style={{fontSize:11,fontWeight:700,color:"#7C3AED",textDecoration:"none"}}>📞 {h.phone}</a>}
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* ── Temples & Places of Worship ── */}
      <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",margin:"18px 0 10px"}}>
        <h3 className="font-black text-sm" style={{color:C.text}}>🛕 Temples & Places of Worship</h3>
        <span style={{fontSize:11,fontWeight:700,padding:"3px 10px",borderRadius:99,background:"#FFF7ED",color:"#B45309"}}>{TEMPLES.length} listed</span>
      </div>
      <div style={{display:"flex",flexDirection:"column",gap:9,marginBottom:4}}>
        {TEMPLES.map(t=>(
          <div key={t.name} style={{borderRadius:14,background:"#fff",border:"1.5px solid #FDE68A",overflow:"hidden",display:"flex"}}>
            <div style={{width:5,flexShrink:0,background:t.type==="Mosque"?"#059669":t.type==="Church"?"#2563EB":"#D97706"}}/>
            <div style={{flex:1,padding:"11px 12px"}}>
              <div style={{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:6,marginBottom:4}}>
                <div style={{display:"flex",alignItems:"center",gap:7}}>
                  <span style={{fontSize:20}}>{t.icon}</span>
                  <div>
                    <div style={{fontWeight:800,fontSize:13,color:"#1F2937",lineHeight:1.2}}>{t.name}</div>
                    <div style={{fontSize:11,color:"#6B7280",marginTop:1}}>{t.area}</div>
                  </div>
                </div>
                <span style={{flexShrink:0,fontSize:10,fontWeight:700,padding:"2px 7px",borderRadius:99,background:t.type==="Mosque"?"#DCFCE7":t.type==="Church"?"#EFF6FF":"#FFFBEB",color:t.type==="Mosque"?"#059669":t.type==="Church"?"#2563EB":"#B45309",whiteSpace:"nowrap"}}>{t.type}</span>
              </div>
              <div style={{fontSize:12,color:"#4B5563",lineHeight:1.5,marginBottom:5}}>{t.desc}</div>
              <div style={{display:"flex",alignItems:"center",gap:5}}><span style={{fontSize:11}}>🕐</span><span style={{fontSize:11,fontWeight:600,color:"#6B7280"}}>{t.timings}</span></div>
            </div>
          </div>
        ))}
      </div>

      {/* ── Cinemas & Entertainment ── */}
      <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",margin:"18px 0 10px"}}>
        <h3 className="font-black text-sm" style={{color:C.text}}>🎬 Cinemas & Entertainment</h3>
        <span style={{fontSize:11,fontWeight:700,padding:"3px 10px",borderRadius:99,background:"#ECFEFF",color:"#0891B2"}}>{CINEMAS.length} venues</span>
      </div>
      <div style={{display:"flex",flexDirection:"column",gap:9,marginBottom:4}}>
        {CINEMAS.map(c=>(
          <div key={c.name} style={{borderRadius:14,background:"#fff",border:"1.5px solid #A5F3FC",overflow:"hidden",display:"flex"}}>
            <div style={{width:5,flexShrink:0,background:c.type==="Multiplex"?"#0891B2":"#6B7280"}}/>
            <div style={{flex:1,padding:"11px 12px"}}>
              <div style={{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:6,marginBottom:4}}>
                <div style={{display:"flex",alignItems:"center",gap:7}}>
                  <span style={{fontSize:20}}>{c.icon}</span>
                  <div>
                    <div style={{fontWeight:800,fontSize:13,color:"#1F2937",lineHeight:1.2}}>{c.name}</div>
                    <div style={{fontSize:11,color:"#6B7280",marginTop:1}}>{c.area}</div>
                  </div>
                </div>
                <span style={{flexShrink:0,fontSize:10,fontWeight:700,padding:"2px 7px",borderRadius:99,background:c.type==="Multiplex"?"#ECFEFF":"#F3F4F6",color:c.type==="Multiplex"?"#0891B2":"#374151",whiteSpace:"nowrap"}}>{c.type}</span>
              </div>
              <div style={{fontSize:12,color:"#4B5563",lineHeight:1.5,marginBottom:5}}>{c.desc}</div>
              <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",flexWrap:"wrap",gap:4}}>
                <div style={{display:"flex",alignItems:"center",gap:5}}><span style={{fontSize:11}}>🕐</span><span style={{fontSize:11,fontWeight:600,color:"#6B7280"}}>{c.timings}</span></div>
                {c.phone&&<a href={`tel:${c.phone}`} style={{fontSize:11,fontWeight:700,color:"#0891B2",textDecoration:"none"}}>📞 {c.phone}</a>}
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* ── ATMs ── */}
      <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",margin:"18px 0 10px"}}>
        <h3 className="font-black text-sm" style={{color:C.text}}>🏧 ATMs</h3>
        <span style={{fontSize:11,fontWeight:700,padding:"3px 10px",borderRadius:99,background:"#DCFCE7",color:"#059669"}}>{ATMS.length} ATMs</span>
      </div>
      <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8,marginBottom:4}}>
        {ATMS.map(a=>(
          <div key={a.name} style={{borderRadius:12,background:"#fff",border:"1.5px solid #A7F3D0",padding:"10px 11px"}}>
            <div style={{display:"flex",alignItems:"center",gap:7,marginBottom:4}}>
              <span style={{fontSize:18}}>{a.icon}</span>
              <div style={{minWidth:0}}>
                <div style={{fontWeight:800,fontSize:12,color:"#1F2937",lineHeight:1.2,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}}>{a.type}</div>
                <div style={{fontSize:10,color:"#6B7280"}}>{a.area}</div>
              </div>
            </div>
            <div style={{display:"flex",alignItems:"center",gap:4}}>
              <span style={{width:6,height:6,borderRadius:"50%",background:"#10B981",flexShrink:0,display:"inline-block"}}/>
              <span style={{fontSize:10,fontWeight:600,color:"#059669"}}>{a.timings}</span>
            </div>
          </div>
        ))}
      </div>
      {/* ── Restaurants & Cafés ── */}
      <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",margin:"18px 0 10px"}}>
        <h3 className="font-black text-sm" style={{color:C.text}}>🍽️ Restaurants & Cafés</h3>
        <span style={{fontSize:11,fontWeight:700,padding:"3px 10px",borderRadius:99,background:"#FEF2F2",color:"#DC2626"}}>{RESTAURANTS.length} listed</span>
      </div>
      <div style={{display:"flex",flexDirection:"column",gap:9}}>
        {RESTAURANTS.map(r=>{
          const typeColor = r.type.includes("South Indian")||r.type.includes("Darshini")?"#B45309":r.type.includes("Veg")?"#059669":r.type.includes("Café")||r.type.includes("Coffee")?"#0891B2":"#DC2626";
          const typeBg    = r.type.includes("South Indian")||r.type.includes("Darshini")?"#FFF7ED":r.type.includes("Veg")?"#DCFCE7":r.type.includes("Café")||r.type.includes("Coffee")?"#ECFEFF":"#FEF2F2";
          return(
            <div key={r.name} style={{borderRadius:14,background:"#fff",border:"1.5px solid #FECACA",overflow:"hidden",display:"flex"}}>
              <div style={{width:5,flexShrink:0,background:typeColor}}/>
              <div style={{flex:1,padding:"11px 12px"}}>
                <div style={{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:6,marginBottom:4}}>
                  <div style={{display:"flex",alignItems:"center",gap:7}}>
                    <span style={{fontSize:20}}>{r.icon}</span>
                    <div>
                      <div style={{fontWeight:800,fontSize:13,color:"#1F2937",lineHeight:1.2}}>{r.name}</div>
                      <div style={{fontSize:11,color:"#6B7280",marginTop:1}}>{r.area}</div>
                    </div>
                  </div>
                  <span style={{flexShrink:0,fontSize:10,fontWeight:700,padding:"2px 7px",borderRadius:99,background:typeBg,color:typeColor,whiteSpace:"nowrap"}}>{r.type}</span>
                </div>
                <div style={{fontSize:12,color:"#4B5563",lineHeight:1.5,marginBottom:5}}>{r.desc}</div>
                <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",flexWrap:"wrap",gap:4}}>
                  <div style={{display:"flex",alignItems:"center",gap:5}}><span style={{fontSize:11}}>🕐</span><span style={{fontSize:11,fontWeight:600,color:"#6B7280"}}>{r.timings}</span></div>
                  {r.phone&&<a href={`tel:${r.phone}`} style={{fontSize:11,fontWeight:700,color:"#DC2626",textDecoration:"none"}}>📞 {r.phone}</a>}
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function MessagesScreen(){
  const [active,setActive]=useState(null);
  const [chat,setChat]=useState([{from:"them",text:"Is the golden retriever still with you?",time:"10:23 AM"},{from:"me",text:"Yes! She is doing well 🐕",time:"10:25 AM"}]);
  const [input,setInput]=useState("");
  const [chatMenu,setChatMenu]=useState(false);
  const [msgBlocking,setMsgBlocking]=useState(null);   // person object | null
  const [msgReporting,setMsgReporting]=useState(null); // person object | null
  const [blockedMsg,setBlockedMsg]=useState(new Set());
  const [viewProfile,setViewProfile]=useState(null);   // person object | null
  const [mutedChats,setMutedChats]=useState(new Set());
  const send=()=>{ if(!input.trim())return; setChat(c=>[...c,{from:"me",text:input.trim(),time:"Now"}]); setInput(""); };
  const m=active!==null?MSGS[active]:null;
  if(m) return(
    <div className="flex flex-col" style={{minHeight:"calc(100vh - 120px)"}}>
      {/* View profile sheet */}
      {viewProfile&&<UserProfileSheet person={viewProfile} onClose={()=>setViewProfile(null)} onBlock={()=>setMsgBlocking(viewProfile)} onReport={()=>setMsgReporting(viewProfile)}/>}
      {/* Block confirm sheet from messages */}
      {msgBlocking&&<BlockConfirmSheet name={msgBlocking.name} onConfirm={()=>{setBlockedMsg(s=>{const n=new Set(s);n.add(msgBlocking.name);return n;});setActive(null);}} onClose={()=>setMsgBlocking(null)}/>}
      {/* Report sheet from messages */}
      {msgReporting&&<ReportSheet type="user" name={msgReporting.name} onClose={()=>setMsgReporting(null)}/>}
      {/* ⋮ menu backdrop */}
      {chatMenu&&<div style={{position:"fixed",inset:0,zIndex:90}} onClick={()=>setChatMenu(false)}/>}
      <div className="px-4 py-3 flex items-center gap-3 sticky top-0 z-20" style={{background:"#fff",borderBottom:`1.5px solid ${C.border}`}}>
        <button onClick={()=>setActive(null)} className="w-8 h-8 rounded-xl flex items-center justify-center font-bold" style={{background:C.purpleFg,color:C.purple}}>←</button>
        <Avatar initials={m.av} color={m.avC} size={38}/>
        <div style={{flex:1}}>
          <div className="font-black text-sm" style={{color:C.text}}>{m.name}</div>
          <div className="text-xs font-bold" style={{color:mutedChats.has(m.name)?"#7C7290":C.mint}}>
            {mutedChats.has(m.name)?"🔇 Muted":"✓ Verified · Online"}
          </div>
        </div>
        {/* ⋮ chat menu */}
        <div style={{position:"relative"}}>
          <button onClick={()=>setChatMenu(v=>!v)}
            style={{width:34,height:34,borderRadius:10,background:C.purpleFg,border:"none",cursor:"pointer",fontSize:22,display:"flex",alignItems:"center",justifyContent:"center",color:C.purple,lineHeight:1}}>⋮</button>
          {chatMenu&&(
            <div style={{position:"absolute",right:0,top:40,background:"#fff",borderRadius:16,boxShadow:"0 8px 32px rgba(28,15,60,0.16)",border:`1px solid ${C.border}`,zIndex:100,minWidth:210,overflow:"hidden"}} onClick={e=>e.stopPropagation()}>
              <button onClick={()=>{setChatMenu(false);setViewProfile(m);}}
                style={{width:"100%",padding:"14px 18px",textAlign:"left",border:"none",cursor:"pointer",background:"transparent",fontSize:13,fontWeight:700,color:C.text,display:"flex",alignItems:"center",gap:12}}>👤 View Profile</button>
              <button onClick={()=>{setMutedChats(s=>{const n=new Set(s);s.has(m.name)?n.delete(m.name):n.add(m.name);return n;});setChatMenu(false);}}
                style={{width:"100%",padding:"14px 18px",textAlign:"left",border:"none",cursor:"pointer",background:mutedChats.has(m.name)?"#F0FFF4":"transparent",fontSize:13,fontWeight:700,color:mutedChats.has(m.name)?"#059669":C.text,display:"flex",alignItems:"center",gap:12,borderTop:`1px solid ${C.border}`}}>
                {mutedChats.has(m.name)?"🔔 Unmute Conversation":"🔇 Mute Conversation"}
              </button>
              <button onClick={()=>{setChatMenu(false);setMsgReporting(m);}}
                style={{width:"100%",padding:"14px 18px",textAlign:"left",border:"none",cursor:"pointer",background:"transparent",fontSize:13,fontWeight:700,color:"#D97706",display:"flex",alignItems:"center",gap:12,borderTop:`1px solid ${C.border}`}}>⚑ Report {m.name}</button>
              <button onClick={()=>{setChatMenu(false);setMsgBlocking(m);}}
                style={{width:"100%",padding:"14px 18px",textAlign:"left",border:"none",cursor:"pointer",background:"#FFF0F1",fontSize:13,fontWeight:900,color:"#FF6B7A",display:"flex",alignItems:"center",gap:12,borderTop:`1px solid ${C.border}`}}>🚫 Block {m.name}</button>
            </div>
          )}
        </div>
      </div>
      <div className="flex-1 p-4 space-y-3 overflow-y-auto" style={{background:C.surface,minHeight:300}}>
        {mutedChats.has(m.name)&&(
          <div style={{textAlign:"center",padding:"8px 16px",borderRadius:12,background:"#F5F4F7",border:"1px solid #ECEAF4",marginBottom:8}}>
            <span style={{fontSize:12,fontWeight:700,color:"#7C7290"}}>🔇 You've muted this conversation. Tap ⋮ → Unmute to receive notifications again.</span>
          </div>
        )}
        {chat.map((msg,i)=>(
          <div key={i} className={`flex ${msg.from==="me"?"justify-end":"justify-start"}`}>
            <div className="max-w-xs px-4 py-2.5 text-sm rounded-2xl"
              style={msg.from==="me"?{background:C.purple,color:"#fff",borderBottomRightRadius:4}:{background:"#fff",color:C.text,borderBottomLeftRadius:4,border:`1.5px solid ${C.border}`}}>
              {msg.text}
              <div className="text-xs mt-1" style={{color:msg.from==="me"?"#D4BCFF":C.muted}}>{msg.time}</div>
            </div>
          </div>
        ))}
      </div>
      <div className="p-4 flex gap-2" style={{background:"#fff",borderTop:`1.5px solid ${C.border}`}}>
        <div className="flex-1 rounded-2xl px-4 py-2.5 flex items-center"
          style={{background:C.surface,border:`1.5px solid ${C.border}`}}>
          <PIIInput value={input} onChange={setInput} placeholder="Type a message…"/>
        </div>
        <button onClick={send} className="w-10 h-10 rounded-2xl flex items-center justify-center text-white font-black flex-shrink-0" style={{background:C.purple}}>↑</button>
      </div>
    </div>
  );
  return(
    <div className="p-3 pb-24">
      <h2 className="font-black text-lg mb-4" style={{color:C.text}}>Messages</h2>
      <div className="rounded-2xl px-4 py-2.5 flex items-center gap-2 mb-4" style={{background:"#fff",border:`1.5px solid ${C.border}`}}>
        <span style={{color:C.muted}}>🔍</span>
        <input className="flex-1 text-sm bg-transparent focus:outline-none" placeholder="Search conversations…" style={{color:C.text}}/>
      </div>
      <div style={{display:"flex",flexDirection:"column",gap:6}}>
        {MSGS.map((msg,i)=>(
          <button key={msg.id} onClick={()=>{setActive(i);setChat([{from:"them",text:msg.preview,time:msg.time}]);}}
            style={{
              width:"100%",borderRadius:18,padding:"12px 14px",
              display:"flex",alignItems:"center",gap:12,
              textAlign:"left",border:"none",cursor:"pointer",
              background:msg.unread>0?"linear-gradient(135deg,rgba(0,184,159,0.05),#fff)":"#fff",
              boxShadow:msg.unread>0?"0 3px 16px rgba(0,184,159,0.12)":"0 2px 8px rgba(28,15,60,0.06)",
              borderLeft:msg.unread>0?`3px solid ${C.mint}`:"3px solid transparent",
            }}>
            <div style={{position:"relative",flexShrink:0}}>
              <div style={{
                width:48,height:48,borderRadius:16,
                background:`linear-gradient(135deg,${msg.avC},${msg.avC}AA)`,
                display:"flex",alignItems:"center",justifyContent:"center",
                color:"#fff",fontWeight:900,fontSize:16,
                boxShadow:`0 3px 10px ${msg.avC}44`,
              }}>{msg.av}</div>
              {msg.unread>0&&<span style={{
                position:"absolute",top:-4,right:-4,
                width:20,height:20,borderRadius:"50%",
                background:"linear-gradient(135deg,#E11D48,#FF6B7A)",
                color:"#fff",fontWeight:900,fontSize:10,
                display:"flex",alignItems:"center",justifyContent:"center",
                border:"2px solid #fff",boxShadow:"0 2px 6px rgba(225,29,72,0.4)",
              }}>{msg.unread}</span>}
            </div>
            <div style={{flex:1,minWidth:0}}>
              <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:3}}>
                <span style={{fontWeight:900,fontSize:13,color:C.text}}>{msg.name}</span>
                <span style={{fontSize:10,color:C.muted}}>{msg.time}</span>
              </div>
              <div style={{fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:msg.unread>0?C.text:C.muted,fontWeight:msg.unread>0?700:400}}>{msg.preview}</div>
            </div>
          </button>
        ))}
      </div>
    </div>
  );
}

function ProfileMenuSheet({item,onBack}){
  const [ic,title,sub]=item;
  const [notifs,setNotifs]=useState({reactions:true,alerts:true,missing:true,events:false,messages:true});
  const [areas,setAreas]=useState({ep1:true,ep2:true,nn:false,bb:false});
  const [privVis,setPrivVis]=useState("Residents Only");
  const [showPhone,setShowPhone]=useState(false);
  const [showApt,setShowApt]=useState(true);
  const Toggle=({on,onToggle,disabled})=>(
    <button onClick={disabled?undefined:onToggle} style={{width:44,height:24,borderRadius:99,border:"none",cursor:disabled?"default":"pointer",background:on?`linear-gradient(135deg,#5C2D91,#8B5CF6)`:"#D1D5DB",position:"relative",opacity:disabled?0.5:1,flexShrink:0,transition:"background 0.2s"}}>
      <div style={{width:18,height:18,borderRadius:"50%",background:"#fff",position:"absolute",top:3,left:on?23:3,transition:"left 0.2s",boxShadow:"0 1px 4px rgba(0,0,0,0.2)"}}/>
    </button>
  );
  const NOTIF_ITEMS=[["reactions","Post Reactions","When someone reacts to your posts"],["alerts","Community Alerts","Safety & emergency alerts"],["missing","Missing Person","Urgent missing person alerts"],["events","Event Reminders","Upcoming events in your area"],["messages","Messages","New messages from neighbours"]];
  const AREA_ITEMS=[["ep1","EC Phase 1","Your home area",true],["ep2","EC Phase 2","Nearby area",false],["nn","Neeladri Nagar","Nearby area",false],["bb","Bommasandra","Nearby area",false]];
  const LISTINGS=[{id:1,icon:"🐕",title:"Lost Dog — Golden Retriever",cat:"Lost & Found",time:"2d ago",views:34},{id:2,icon:"🔧",title:"AC Repair Service Recommendation",cat:"Recommendation",time:"5d ago",views:82},{id:3,icon:"🌿",title:"Free plants — come pick up",cat:"General",time:"1w ago",views:19}];
  const FAQS=[["How do I verify my residency?","Upload your Aadhaar + apartment allotment letter. Verification takes 24–48 hours."],["Can I see posts from other areas?","Yes! Go to Area Settings to follow nearby areas."],["How do I report a post?","Long press any post and tap Report. Our team reviews within 2 hours."],["How do I change my apartment?","Contact support below — we will verify your new address and update it."]];
  const contentMap={
    "Notifications":(
      <div>
        {NOTIF_ITEMS.map(([k,lbl,desc])=>(
          <div key={k} style={{display:"flex",alignItems:"center",padding:"14px 0",borderBottom:`1px solid ${C.border}`}}>
            <div style={{flex:1}}><div style={{fontWeight:700,fontSize:13,color:C.text}}>{lbl}</div><div style={{fontSize:11,color:C.muted,marginTop:1}}>{desc}</div></div>
            <Toggle on={notifs[k]} onToggle={()=>setNotifs(n=>({...n,[k]:!n[k]}))}/>
          </div>
        ))}
      </div>
    ),
    "My Apartment":(
      <div>
        {[["🏢","Building","Prestige Sunrise Park"],["🔢","Unit","B-204"],["📍","Area","EC Phase 1 · Bangalore 560100"],["📅","Member Since","January 2025"],["🛡","Status","Verified Resident"]].map(([i,l,v])=>(
          <div key={l} style={{display:"flex",alignItems:"center",gap:12,padding:"13px 0",borderBottom:`1px solid ${C.border}`}}>
            <div style={{width:38,height:38,borderRadius:11,background:C.surface,display:"flex",alignItems:"center",justifyContent:"center",fontSize:18,flexShrink:0}}>{i}</div>
            <div><div style={{fontSize:11,color:C.muted}}>{l}</div><div style={{fontWeight:700,fontSize:14,color:C.text,marginTop:1}}>{v}</div></div>
          </div>
        ))}
        <button style={{width:"100%",marginTop:16,padding:"12px",borderRadius:14,background:C.purpleFg,color:C.purple,fontWeight:700,fontSize:13,border:`1.5px solid ${C.purple}22`,cursor:"pointer"}}>📝 Request Apartment Update</button>
      </div>
    ),
    "Area Settings":(
      <div>
        <div style={{fontSize:12,color:C.muted,marginBottom:12,lineHeight:1.5}}>Choose which areas you want to see posts from. Your home area (EC Phase 1) is always on.</div>
        {AREA_ITEMS.map(([k,lbl,sub2,isHome])=>(
          <div key={k} style={{display:"flex",alignItems:"center",padding:"13px 0",borderBottom:`1px solid ${C.border}`}}>
            <div style={{flex:1}}><div style={{fontWeight:700,fontSize:13,color:C.text}}>{lbl}</div><div style={{fontSize:11,color:isHome?C.mint:C.muted,marginTop:1}}>{isHome?"Your home area":sub2}</div></div>
            <Toggle on={areas[k]} onToggle={()=>setAreas(a=>({...a,[k]:!a[k]}))} disabled={isHome}/>
          </div>
        ))}
      </div>
    ),
    "Privacy & Safety":(
      <div>
        <div style={{fontSize:12,color:C.muted,marginBottom:12,lineHeight:1.5}}>Control who can see your profile and contact you.</div>
        <div style={{marginBottom:12}}>
          <div style={{fontWeight:700,fontSize:13,color:C.text,marginBottom:8}}>Who can see my profile</div>
          {["Everyone","Residents Only","Nobody"].map(v=>(
            <button key={v} onClick={()=>setPrivVis(v)} style={{width:"100%",display:"flex",alignItems:"center",gap:10,padding:"11px 14px",borderRadius:12,marginBottom:6,border:`1.5px solid ${privVis===v?C.purple:C.border}`,background:privVis===v?C.purpleFg:"#fff",cursor:"pointer",textAlign:"left"}}>
              <div style={{width:18,height:18,borderRadius:"50%",border:`2px solid ${privVis===v?C.purple:C.border}`,display:"flex",alignItems:"center",justifyContent:"center"}}>{privVis===v&&<div style={{width:9,height:9,borderRadius:"50%",background:C.purple}}/>}</div>
              <span style={{fontWeight:600,fontSize:13,color:privVis===v?C.purple:C.text}}>{v}</span>
            </button>
          ))}
        </div>
        {[[showPhone,(v)=>setShowPhone(v),"Show phone number","Only shared with verified connections"],[showApt,(v)=>setShowApt(v),"Show apartment number","Visible to area residents"]].map(([val,setter,lbl,desc])=>(
          <div key={lbl} style={{display:"flex",alignItems:"center",padding:"13px 0",borderBottom:`1px solid ${C.border}`}}>
            <div style={{flex:1}}><div style={{fontWeight:700,fontSize:13,color:C.text}}>{lbl}</div><div style={{fontSize:11,color:C.muted,marginTop:1}}>{desc}</div></div>
            <Toggle on={val} onToggle={()=>setter(v=>!v)}/>
          </div>
        ))}
      </div>
    ),
    "My Listings":(
      <div>
        {LISTINGS.map(l=>(
          <div key={l.id} style={{display:"flex",gap:10,alignItems:"flex-start",padding:"13px 0",borderBottom:`1px solid ${C.border}`}}>
            <div style={{width:40,height:40,borderRadius:12,background:C.surface,display:"flex",alignItems:"center",justifyContent:"center",fontSize:20,flexShrink:0}}>{l.icon}</div>
            <div style={{flex:1}}><div style={{fontWeight:700,fontSize:13,color:C.text}}>{l.title}</div><div style={{fontSize:11,color:C.muted,marginTop:2}}>{l.cat} · {l.time}</div><div style={{fontSize:10,color:C.mint,marginTop:3,fontWeight:600}}>👁 {l.views} views · Active</div></div>
            <button style={{fontSize:11,padding:"4px 10px",borderRadius:8,background:C.purpleFg,color:C.purple,border:`1px solid ${C.purple}22`,cursor:"pointer",fontWeight:700,flexShrink:0}}>Edit</button>
          </div>
        ))}
        <button style={{width:"100%",marginTop:14,padding:"12px",borderRadius:14,background:`linear-gradient(135deg,#5C2D91,#8B5CF6)`,color:"#fff",fontWeight:700,fontSize:13,border:"none",cursor:"pointer"}}>＋ New Listing</button>
      </div>
    ),
    "Verification":(
      <div>
        <div style={{padding:"16px",borderRadius:16,background:"linear-gradient(135deg,#E0F7F4,#B2EFE6)",border:"1.5px solid #00B89F44",marginBottom:16,textAlign:"center"}}>
          <div style={{fontSize:40,marginBottom:8}}>✅</div>
          <div style={{fontWeight:900,fontSize:16,color:C.text}}>Verified Resident</div>
          <div style={{fontSize:12,color:C.muted,marginTop:4}}>Identity and Residency Confirmed</div>
        </div>
        {[["📋","ID Type","Aadhaar Card"],["📅","Verified On","14 January 2025"],["🏢","Property","Prestige Sunrise Park · B-204"],["🔒","Status","Active · Trusted Member"]].map(([i,l,v])=>(
          <div key={l} style={{display:"flex",alignItems:"center",gap:12,padding:"11px 0",borderBottom:`1px solid ${C.border}`}}>
            <div style={{width:34,height:34,borderRadius:10,background:C.surface,display:"flex",alignItems:"center",justifyContent:"center",fontSize:16,flexShrink:0}}>{i}</div>
            <div><div style={{fontSize:11,color:C.muted}}>{l}</div><div style={{fontWeight:700,fontSize:13,color:C.text,marginTop:1}}>{v}</div></div>
          </div>
        ))}
      </div>
    ),
    "Help & Support":(
      <div>
        <div style={{fontWeight:800,fontSize:13,color:C.text,marginBottom:10}}>Frequently Asked Questions</div>
        {FAQS.map(([q,a])=>(
          <details key={q} style={{marginBottom:8,borderRadius:12,overflow:"hidden",border:`1px solid ${C.border}`}}>
            <summary style={{padding:"12px 14px",fontWeight:700,fontSize:13,color:C.text,cursor:"pointer",background:"#fff",listStyle:"none",display:"flex",justifyContent:"space-between",alignItems:"center"}}>{q}<span style={{color:C.muted}}>›</span></summary>
            <div style={{padding:"10px 14px 14px",fontSize:12,color:C.muted,lineHeight:1.6,background:C.surface}}>{a}</div>
          </details>
        ))}
        <div style={{marginTop:14,padding:"14px",borderRadius:14,background:C.purpleFg,border:`1.5px solid ${C.purple}22`}}>
          <div style={{fontWeight:700,fontSize:13,color:C.text,marginBottom:4}}>📧 Contact Support</div>
          <div style={{fontSize:12,color:C.muted,marginBottom:10}}>We typically respond within 2 hours</div>
          <a href="mailto:support@mytown360.in" style={{display:"block",padding:"10px",borderRadius:12,background:`linear-gradient(135deg,#5C2D91,#8B5CF6)`,color:"#fff",fontWeight:700,fontSize:13,textAlign:"center",textDecoration:"none"}}>✉️ support@mytown360.in</a>
        </div>
      </div>
    ),
  };
  return(
    <div style={{minHeight:"100vh",background:C.surface}}>
      <div style={{position:"sticky",top:0,zIndex:10,background:"#fff",borderBottom:`1px solid ${C.border}`,padding:"14px 16px",display:"flex",alignItems:"center",gap:12}}>
        <button onClick={onBack} style={{width:34,height:34,borderRadius:11,background:C.purpleFg,border:"none",color:C.purple,fontWeight:900,fontSize:18,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center"}}>‹</button>
        <div style={{flex:1}}><div style={{fontWeight:900,fontSize:15,color:C.text}}>{title}</div><div style={{fontSize:11,color:C.muted,marginTop:1}}>{sub}</div></div>
        <span style={{fontSize:22}}>{ic}</span>
      </div>
      <div style={{padding:"16px",paddingBottom:96}}>
        {contentMap[title]||<div style={{color:C.muted,textAlign:"center",padding:"32px 0",fontSize:14}}>Coming soon…</div>}
      </div>
    </div>
  );
}

function ProfileScreen({nav}){
  const [menuItem,setMenuItem]=useState(null);
  if(menuItem) return <ProfileMenuSheet item={menuItem} onBack={()=>setMenuItem(null)}/>;
  const MENU=[["🔔","Notifications","Alerts & preferences"],["🏘","My Apartment","Prestige Sunrise Park · B-204"],["🗺","Area Settings","EC Phase 1 & 2"],["🔒","Privacy & Safety","Who can see your profile"],["📋","My Listings","3 active listings"],["🛡","Verification","Verified · Aadhaar Card"],["❓","Help & Support","FAQs and contact us"]];
  return(
    <div style={{paddingBottom:96}}>
      {/* Cover / hero */}
      <div style={{position:"relative",overflow:"hidden",marginBottom:16}}>
        {/* Cover pattern */}
        <div style={{
          height:110,
          background:"linear-gradient(135deg,#2D0854 0%,#5C2D91 50%,#00967E 100%)",
          position:"relative",
        }}>
          <div style={{position:"absolute",inset:0,backgroundImage:"radial-gradient(rgba(255,255,255,0.08) 1px,transparent 1px)",backgroundSize:"18px 18px"}}/>
          <div style={{position:"absolute",top:-30,right:-20,width:130,height:130,borderRadius:"50%",background:"rgba(0,184,159,0.2)",filter:"blur(12px)"}}/>
        </div>
        {/* Avatar overlapping cover */}
        <div style={{padding:"0 16px",position:"relative",marginTop:-40}}>
          <div style={{display:"flex",alignItems:"flex-end",justifyContent:"space-between",marginBottom:10}}>
            <div style={{position:"relative"}}>
              <div style={{
                width:76,height:76,borderRadius:22,
                background:"linear-gradient(135deg,#5C2D91,#8B5CF6)",
                display:"flex",alignItems:"center",justifyContent:"center",
                color:"#fff",fontWeight:900,fontSize:26,
                border:"3px solid #fff",
                boxShadow:"0 4px 20px rgba(92,45,145,0.4)",
              }}>MT</div>
              <div style={{
                position:"absolute",bottom:0,right:-4,
                width:24,height:24,borderRadius:8,
                background:"linear-gradient(135deg,#008F7A,#00B89F)",
                display:"flex",alignItems:"center",justifyContent:"center",
                color:"#fff",fontWeight:900,fontSize:11,
                border:"2px solid #fff",
              }}>✓</div>
            </div>
            <button style={{
              padding:"8px 16px",borderRadius:12,fontSize:12,fontWeight:800,
              border:"none",cursor:"pointer",
              background:"linear-gradient(135deg,#5C2D91,#7B4BB8)",
              color:"#fff",boxShadow:"0 3px 12px rgba(92,45,145,0.35)",
            }}>Edit Profile</button>
          </div>
          {/* Name + badge */}
          <div style={{fontWeight:900,fontSize:20,color:C.text,lineHeight:1.1}}>Meena T.</div>
          <div style={{fontSize:12,color:C.muted,marginTop:2}}>Prestige Sunrise Park · B-204, EC Phase 1</div>
          <div style={{marginTop:6,display:"inline-flex",alignItems:"center",gap:5,padding:"4px 12px",borderRadius:99,background:"linear-gradient(135deg,#E0F7F4,#B2EFE6)",border:"1.5px solid #00B89F44"}}>
            <span style={{fontSize:12}}>✓</span>
            <span style={{fontSize:11,fontWeight:800,color:C.mint}}>Verified Resident · Aadhaar</span>
          </div>
          {/* Floating stat pills */}
          <div style={{display:"flex",gap:8,marginTop:12}}>
            {[["47","Posts","#5C2D91"],["128","Connections","#4F46E5"],["12","Events","#D97706"]].map(([n,l,col])=>(
              <div key={l} style={{
                flex:1,padding:"10px 6px",borderRadius:14,textAlign:"center",
                background:"#fff",boxShadow:"0 3px 14px rgba(28,15,60,0.09)",
                border:`1px solid ${col}18`,
              }}>
                <div style={{fontSize:20,fontWeight:900,color:col}}>{n}</div>
                <div style={{fontSize:10,fontWeight:600,color:C.muted}}>{l}</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Menu list */}
      <div style={{margin:"0 12px 12px",borderRadius:20,overflow:"hidden",background:"#fff",boxShadow:"0 4px 20px rgba(28,15,60,0.08)"}}>
        {MENU.map(([ic,title,sub],i)=>(
          <button key={title} onClick={()=>setMenuItem([ic,title,sub])} style={{
            width:"100%",display:"flex",alignItems:"center",gap:12,
            padding:"13px 16px",textAlign:"left",border:"none",cursor:"pointer",
            borderBottom:i<MENU.length-1?`1px solid ${C.border}`:"none",
            background:"transparent",
          }}>
            <div style={{width:36,height:36,borderRadius:11,background:C.surface,display:"flex",alignItems:"center",justifyContent:"center",fontSize:18,flexShrink:0}}>{ic}</div>
            <div style={{flex:1}}>
              <div style={{fontWeight:700,fontSize:13,color:C.text}}>{title}</div>
              <div style={{fontSize:11,color:C.muted,marginTop:1}}>{sub}</div>
            </div>
            <span style={{color:C.muted,fontWeight:900,fontSize:16}}>›</span>
          </button>
        ))}
      </div>
      {/* Admin Panel — not shown in public UI, access directly via mytown360.in/admin */}
      <div style={{padding:"0 12px"}}>
      <button onClick={()=>nav("landing")} style={{
        width:"100%",padding:"13px",borderRadius:16,fontWeight:800,fontSize:13,
        border:`1.5px solid ${C.rose}44`,color:C.rose,
        background:"linear-gradient(135deg,#FFF1F2,#FFE4E7)",
        cursor:"pointer",marginBottom:20,
      }}>🚪 Sign Out</button>
      <div className="text-center space-y-1">
        <div className="flex items-center justify-center gap-2"><Logo size={18}/><span className="text-sm font-black" style={{color:C.text}}>MyTown 360</span></div>
        <p className="text-xs" style={{color:C.muted}}>mytown360.in · v1.0 · Electronic City, Bangalore 🇮🇳</p>
      </div>
    </div>
    </div>
  );
}

// ─── Community Manager Data ──────────────────────────────────────────────────
// ─── PII Consent Modal ───────────────────────────────────────────────────────
function PIIConsentModal({piiType, onAccept, onDecline}){
  const meta = PII_META[piiType]||PII_META.phone;
  return(
    <div style={{position:"fixed",inset:0,zIndex:200,display:"flex",alignItems:"flex-end",justifyContent:"center",background:"rgba(26,16,51,0.6)",backdropFilter:"blur(4px)"}}>
      <div style={{width:"100%",maxWidth:430,background:"#fff",borderRadius:"24px 24px 0 0",padding:"0 0 36px",animation:"slideUp 0.3s ease"}}>
        <div style={{display:"flex",justifyContent:"center",paddingTop:12}}><div style={{width:40,height:4,borderRadius:99,background:C.border}}/></div>
        {/* Warning header */}
        <div style={{margin:"16px 20px 0",padding:"14px 16px",borderRadius:16,background:"#FFF8E7",border:`1.5px solid ${C.marigold}66`,display:"flex",gap:12,alignItems:"flex-start"}}>
          <span style={{fontSize:28}}>{meta.icon}</span>
          <div>
            <div style={{fontWeight:900,fontSize:15,color:C.text}}>Sensitive Information Detected</div>
            <div style={{fontSize:12,color:C.muted,marginTop:3}}>You are about to share your <span style={{fontWeight:700,color:C.coral}}>{meta.label}</span>.</div>
          </div>
        </div>
        {/* Info */}
        <div style={{margin:"12px 20px 0",fontSize:13,color:C.text,lineHeight:1.6}}>
          <p style={{marginBottom:8}}>{meta.msg}</p>
          <div style={{padding:"12px 14px",borderRadius:12,background:C.coralL,border:`1.5px solid ${C.coral}33`}}>
            <p style={{fontWeight:700,fontSize:12,color:C.coral,marginBottom:4}}>⚠️ Important Disclaimer</p>
            <p style={{fontSize:12,color:C.text,lineHeight:1.5}}>
              MyTown 360 is <strong>not responsible</strong> for any consequences arising from sharing this information.
              This is entirely your personal choice. Once shared, we cannot guarantee how this information will be used by others.
            </p>
          </div>
        </div>
        {/* Consent buttons */}
        <div style={{margin:"16px 20px 0",display:"flex",flexDirection:"column",gap:10}}>
          <button onClick={onAccept}
            style={{width:"100%",padding:"13px",borderRadius:14,background:C.purple,color:"#fff",fontWeight:900,fontSize:14,border:"none",cursor:"pointer"}}>
            ✅ I Accept — Share My {meta.label}
          </button>
          <button onClick={onDecline}
            style={{width:"100%",padding:"13px",borderRadius:14,background:C.coralL,color:C.coral,fontWeight:900,fontSize:14,border:`1.5px solid ${C.coral}33`,cursor:"pointer"}}>
            ❌ Decline — Remove This Information
          </button>
        </div>
      </div>
    </div>
  );
}

// ─── Content Blocked Banner ───────────────────────────────────────────────────
function ContentBlockedBanner({context, onEdit}){
  return(
    <div style={{borderRadius:16,overflow:"hidden",border:`1.5px solid ${C.coral}55`,marginBottom:8}}>
      <div style={{background:`linear-gradient(90deg,${C.coral},#FF9AA5)`,padding:"8px 14px",display:"flex",gap:8,alignItems:"center"}}>
        <span style={{fontSize:16}}>🚫</span>
        <span style={{color:"#fff",fontWeight:900,fontSize:12}}>CONTENT BLOCKED — POLICY VIOLATION</span>
      </div>
      <div style={{background:"#FFF5F5",padding:"12px 14px"}}>
        <p style={{fontSize:12,color:C.text,marginBottom:8,lineHeight:1.5}}>
          This {context} was automatically blocked because it appears to contain <strong>sexual or inappropriate content</strong> that violates our Community Guidelines.
        </p>
        <div style={{display:"flex",gap:8}}>
          {onEdit&&<button onClick={onEdit} style={{flex:1,padding:"7px",borderRadius:10,background:C.purple,color:"#fff",fontWeight:700,fontSize:12,border:"none",cursor:"pointer"}}>✏️ Edit Content</button>}
          <div style={{flex:1,padding:"7px",borderRadius:10,background:C.surface,color:C.muted,fontWeight:600,fontSize:12,textAlign:"center"}}>📋 Report Filed</div>
        </div>
      </div>
    </div>
  );
}

// ─── PII-aware Textarea ────────────────────────────────────────────────────────
// Detects PII as user types; shows consent modal before allowing sensitive content
function PIITextarea({value, onChange, placeholder, rows=3, style={}}){
  const [showConsent,setShowConsent]=useState(false);
  const [pending,setPending]=useState("");
  const [piiType,setPiiType]=useState(null);
  const [accepted,setAccepted]=useState(new Set());
  const handleChange=(e)=>{
    const v=e.target.value;
    const detected=detectPII(v);
    if(detected&&!accepted.has(detected)){ setPending(v);setPiiType(detected);setShowConsent(true); }
    else{ onChange(v); }
  };
  const accept=()=>{ setAccepted(p=>new Set([...p,piiType]));onChange(pending);setShowConsent(false); };
  const decline=()=>{ setShowConsent(false); /* keep old value, don't update */ };
  return(
    <>
      {showConsent&&<PIIConsentModal piiType={piiType} onAccept={accept} onDecline={decline}/>}
      <textarea rows={rows} value={value} onChange={handleChange} placeholder={placeholder}
        className="w-full rounded-xl p-3 text-sm resize-none focus:outline-none"
        style={{background:C.surface,border:`1.5px solid ${C.border}`,color:C.text,...style}}/>
    </>
  );
}

// ─── PII-aware Input ──────────────────────────────────────────────────────────
function PIIInput({value, onChange, placeholder, style={}}){
  const [showConsent,setShowConsent]=useState(false);
  const [pending,setPending]=useState("");
  const [piiType,setPiiType]=useState(null);
  const [accepted,setAccepted]=useState(new Set());
  const handleChange=(e)=>{
    const v=e.target.value;
    const detected=detectPII(v);
    if(detected&&!accepted.has(detected)){ setPending(v);setPiiType(detected);setShowConsent(true); }
    else{ onChange(v); }
  };
  const accept=()=>{ setAccepted(p=>new Set([...p,piiType]));onChange(pending);setShowConsent(false); };
  const decline=()=>{ setShowConsent(false); };
  return(
    <>
      {showConsent&&<PIIConsentModal piiType={piiType} onAccept={accept} onDecline={decline}/>}
      <input value={value} onChange={handleChange} placeholder={placeholder}
        className="flex-1 text-sm bg-transparent focus:outline-none"
        style={{color:C.text,...style}}/>
    </>
  );
}

// ─── Ineligibility Modal ────────────────────────────────────────────────────
function IneligibilityModal({onClose, stats, candidateCount}){
  const checks=[
    { ok:stats.verified,         label:"Verified Resident",         detail:"Government ID + address proof must be verified",     fix:"Complete verification in your Profile" },
    { ok:stats.eventsOrg>=5,     label:`Organised 5+ Events (you: ${stats.eventsOrg})`, detail:"Must have organised at least 5 community events",  fix:"Organise more events from the Events tab" },
    { ok:stats.posts>=10,        label:`10+ Community Posts (you: ${stats.posts})`,      detail:"Must be an active poster in neighbourhood feed",   fix:"Engage more in the Neighbourhood Feed" },
    { ok:stats.area!==undefined, label:"Same Area Resident",         detail:"Can only apply for your own registered area",        fix:"Your area is auto-detected from your address" },
    { ok:candidateCount<4,       label:`Slot Available (${candidateCount}/4 taken)`,     detail:"Maximum 4 candidates per election",                fix:"Wait for next election cycle" },
  ];
  const passed=checks.filter(c=>c.ok).length;
  return(
    <div style={{position:"fixed",inset:0,zIndex:100,display:"flex",alignItems:"flex-end",justifyContent:"center",background:"rgba(26,16,51,0.55)",backdropFilter:"blur(4px)"}}>
      <div style={{width:"100%",maxWidth:430,background:"#fff",borderRadius:"24px 24px 0 0",padding:"0 0 32px",maxHeight:"90vh",overflowY:"auto"}}>
        {/* Handle bar */}
        <div style={{display:"flex",justifyContent:"center",paddingTop:12,paddingBottom:4}}>
          <div style={{width:40,height:4,borderRadius:99,background:C.border}}/>
        </div>
        {/* Header */}
        <div style={{padding:"12px 20px 16px",borderBottom:`1.5px solid ${C.border}`}}>
          <div style={{display:"flex",alignItems:"center",justifyContent:"space-between"}}>
            <div>
              <div style={{fontWeight:900,fontSize:16,color:C.text}}>Eligibility Check</div>
              <div style={{fontSize:12,color:C.muted,marginTop:2}}>You meet <span style={{fontWeight:800,color:passed===checks.length?C.mint:C.coral}}>{passed}/{checks.length}</span> conditions to apply</div>
            </div>
            <button onClick={onClose} style={{width:32,height:32,borderRadius:10,background:C.surface,border:`1.5px solid ${C.border}`,fontWeight:900,fontSize:14,cursor:"pointer",color:C.muted}}>✕</button>
          </div>
          {/* Progress bar */}
          <div style={{marginTop:12,height:6,borderRadius:99,background:C.border}}>
            <div style={{height:6,borderRadius:99,background:passed===checks.length?C.mint:C.coral,width:`${(passed/checks.length)*100}%`,transition:"width 0.5s"}}/>
          </div>
        </div>
        {/* Conditions list */}
        <div style={{padding:"12px 20px 0"}}>
          {checks.map((c,i)=>(
            <div key={i} style={{display:"flex",gap:12,padding:"12px 0",borderBottom:i<checks.length-1?`1px solid ${C.border}`:"none"}}>
              <div style={{width:28,height:28,borderRadius:99,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,fontSize:14,background:c.ok?C.mintL:C.coralL}}>
                {c.ok?"✅":"❌"}
              </div>
              <div style={{flex:1}}>
                <div style={{fontWeight:700,fontSize:13,color:c.ok?C.text:C.muted}}>{c.label}</div>
                <div style={{fontSize:11,color:C.muted,marginTop:1}}>{c.detail}</div>
                {!c.ok&&<div style={{fontSize:11,fontWeight:600,color:C.coral,marginTop:3}}>→ {c.fix}</div>}
              </div>
            </div>
          ))}
        </div>
        {/* Footer CTA */}
        <div style={{padding:"16px 20px 0"}}>
          {passed===checks.length?(
            <button onClick={onClose} style={{width:"100%",padding:"12px",borderRadius:14,background:C.purple,color:"#fff",fontWeight:900,fontSize:14,border:"none",cursor:"pointer"}}>
              ✅ You're Eligible · Continue to Apply →
            </button>
          ):(
            <div style={{borderRadius:14,padding:"12px 14px",background:C.coralL,border:`1.5px solid ${C.coral}33`}}>
              <div style={{fontWeight:700,fontSize:12,color:C.coral}}>❌ Not yet eligible</div>
              <div style={{fontSize:11,color:C.muted,marginTop:3}}>Complete the conditions above before the application deadline. Check back once you meet all requirements.</div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ─── Community Manager Screen ────────────────────────────────────────────────
function CommunityManagerScreen(){
  const [selArea,  setSelArea]  = useState("ep2");
  const [voted,    setVoted]    = useState(null);
  const [view,     setView]     = useState("main");
  const [applyStep,setApplyStep]= useState(1);
  const [applyForm,setApplyForm]= useState({photo:"",proof:"",profession:"",statement:""});
  const [voteAnim, setVoteAnim] = useState(null);
  const [showIneligible, setShowIneligible] = useState(false);

  const phase     = ELECTION_PHASES[selArea];
  const term      = TERM_DATA[selArea] || {};
  const manager   = CURRENT_MANAGERS[selArea];
  const candidates= CANDIDATES_BY_AREA[selArea] || [];
  const totalVotes= candidates.reduce((s,c)=>s+c.votes,0) + (voted?1:0);
  const meInArea  = MY_STATS.area === selArea;
  const meEligible= MY_STATS.verified && MY_STATS.eventsOrg>=5 && MY_STATS.posts>=10 && candidates.length<4;
  const doVote=(id)=>{ setVoteAnim(id); setTimeout(()=>{setVoted(id);setVoteAnim(null);},600); };

  const handleApplyClick=()=>{
    if(meEligible) setView("apply");
    else setShowIneligible(true);
  };

  if(view==="apply") return <CMApplyScreen step={applyStep} setStep={setApplyStep} form={applyForm} setForm={setApplyForm} onDone={()=>setView("success")} onBack={()=>setView("main")} area={CM_AREAS.find(a=>a.id===selArea)}/>;
  if(view==="success") return <CMSuccessScreen onBack={()=>{setView("main");setApplyStep(1);}}/>;

  return(
    <div className="px-4 py-4 space-y-4">
      {showIneligible&&<IneligibilityModal onClose={()=>setShowIneligible(false)} stats={MY_STATS} candidateCount={candidates.length}/>}

      {/* Title */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-xl font-black" style={{color:C.text}}>Community Admins</h2>
          <p className="text-xs mt-0.5" style={{color:C.muted}}>6-month term · Top 4 shortlisted · Area residents vote</p>
        </div>
        <span className="text-xs font-bold px-2.5 py-1 rounded-xl" style={{background:C.purpleFg,color:C.purple}}>🔄 Every 6 months</span>
      </div>

      {/* Area selector */}
      <div className="flex gap-2 overflow-x-auto pb-1">
        {CM_AREAS.map(a=>{
          const ph=ELECTION_PHASES[a.id];
          const badge = ph==="voting"?"🗳":ph==="pre_election"?"📣":ph==="stable"?"✅":"🏛";
          return(
            <button key={a.id} onClick={()=>setSelArea(a.id)}
              className="flex-shrink-0 px-3 py-1.5 rounded-xl text-xs font-black transition-all"
              style={selArea===a.id?{background:C.purple,color:"#fff"}:{background:C.surface,color:C.muted,border:`1.5px solid ${C.border}`}}>
              {badge} {a.label}
            </button>
          );
        })}
      </div>

      {/* ── ELECTION NOTIFICATION BANNER (pre_election phase) ── */}
      {phase==="pre_election" && (
        <div className="rounded-2xl overflow-hidden" style={{border:`1.5px solid ${C.marigold}55`}}>
          <div className="px-4 py-2 flex items-center gap-2" style={{background:`linear-gradient(90deg,${C.marigold},#FFD580)`}}>
            <span className="text-sm">📣</span>
            <span className="font-black text-xs text-white">ELECTION NOTIFICATION — Sent to all {selArea.toUpperCase()} members</span>
          </div>
          <div className="px-4 py-3" style={{background:"#FFFDF0"}}>
            <p className="text-xs leading-relaxed" style={{color:C.text}}>
              <span className="font-black">Current admin's term ends in 30 days.</span> The next Community Admin election for <span className="font-bold" style={{color:C.marigold}}>{CM_AREAS.find(a=>a.id===selArea)?.label}</span> is now open for applications. Eligible residents can apply before <span className="font-bold">{term.applyDeadline}</span>. Top 4 by activity score will be shortlisted for community voting.
            </p>
            <div className="flex gap-2 mt-2 flex-wrap">
              <span className="text-xs px-2 py-0.5 rounded-full font-bold" style={{background:C.marigoldL,color:"#B87A00"}}>Applications: {term.applicantsCount}/4</span>
              <span className="text-xs px-2 py-0.5 rounded-full font-bold" style={{background:C.coralL,color:C.coral}}>Deadline: {term.applyDeadline}</span>
            </div>
          </div>
        </div>
      )}

      {/* ── CURRENT ADMIN + TERM CARD ── */}
      {manager && (
        <div className="rounded-2xl overflow-hidden" style={{background:"#fff",border:`1.5px solid ${C.purple}22`}}>
          <div className="px-4 py-2 flex items-center gap-2" style={{background:`linear-gradient(90deg,${C.purple},${C.purpleL})`}}>
            <span className="text-white text-xs font-black">👑 CURRENT COMMUNITY ADMIN · 6-MONTH TERM</span>
          </div>
          <div className="px-4 pt-3 pb-1 flex items-center gap-3">
            <div className="w-14 h-14 rounded-2xl flex items-center justify-center text-white font-black text-lg flex-shrink-0"
              style={{background:manager.color}}>{manager.avatar}</div>
            <div className="flex-1">
              <div className="font-black text-sm" style={{color:C.text}}>{manager.name}</div>
              <div className="text-xs" style={{color:C.muted}}>{manager.apt}</div>
              <div className="flex gap-2 mt-1.5 flex-wrap">
                <span className="text-xs font-bold px-2 py-0.5 rounded-full" style={{background:C.purpleFg,color:C.purple}}>{term.termStart} – {term.termEnd}</span>
                <span className="text-xs font-bold px-2 py-0.5 rounded-full" style={{background:C.mintL,color:C.mint}}>✅ Verified</span>
              </div>
            </div>
          </div>
          {/* Term progress bar */}
          {phase==="stable" && term.totalDays && (
            <div className="px-4 pb-3">
              <div className="flex items-center justify-between text-xs mb-1.5">
                <span style={{color:C.muted}}>Term Progress</span>
                <span style={{fontWeight:700,color:C.purple}}>{term.daysLeft} days remaining</span>
              </div>
              <div className="rounded-full h-3" style={{background:C.border,position:"relative"}}>
                <div className="h-3 rounded-full" style={{width:`${Math.min(100,(term.daysElapsed/term.totalDays)*100)}%`,background:`linear-gradient(90deg,${C.purple},${C.mint})`}}/>
              </div>
              <div className="flex justify-between text-xs mt-1" style={{color:C.muted}}>
                <span>{term.termStart}</span>
                <span>Next election opens: <span style={{fontWeight:700,color:C.marigold}}>{term.nextElectionOpen}</span></span>
                <span>{term.termEnd}</span>
              </div>
            </div>
          )}
          {/* Pre-election warning */}
          {phase==="pre_election" && (
            <div className="mx-4 mb-3 rounded-xl px-3 py-2" style={{background:C.marigoldL,border:`1.5px solid ${C.marigold}44`}}>
              <div className="text-xs font-black" style={{color:"#B87A00"}}>⚠️ Term ending soon — Election notifications sent to all members</div>
              <div className="text-xs mt-0.5" style={{color:C.muted}}>Applications are now open. Current admin finishes on {term.termEnd}.</div>
            </div>
          )}
          {/* Contact button */}
          <div className="px-4 pb-3">
            <button className="w-full py-2 rounded-xl text-sm font-bold transition-all active:scale-95"
              style={{background:C.purpleFg,color:C.purple,border:`1.5px solid ${C.purple}22`}}>
              📞 Contact {manager.name.split(" ")[0]}
            </button>
          </div>
        </div>
      )}

      {/* No admin state */}
      {!manager && phase!=="voting" && (
        <div className="rounded-2xl px-4 py-4 flex items-center gap-3" style={{background:C.marigoldL,border:`1.5px solid ${C.marigold}44`}}>
          <span className="text-2xl">🏛</span>
          <div>
            <div className="font-black text-sm" style={{color:C.text}}>No Community Admin yet</div>
            <div className="text-xs mt-0.5" style={{color:C.muted}}>{term.note||"Apply to start the first election for this area!"}</div>
          </div>
        </div>
      )}

      {/* ── VOTING PHASE: Shortlist banner ── */}
      {phase==="voting" && (
        <div className="rounded-2xl overflow-hidden" style={{border:`1.5px solid ${C.coral}44`}}>
          <div className="px-4 py-2 flex items-center justify-between" style={{background:`linear-gradient(90deg,${C.coral},#FF9AA5)`}}>
            <span className="text-white font-black text-xs">🗳 VOTING IN PROGRESS</span>
            <span className="text-white text-xs font-bold">{term.daysLeftVoting} days left</span>
          </div>
          {/* Top-4 selection explanation */}
          <div className="px-4 py-3" style={{background:"#FFF8F9"}}>
            <div className="text-xs font-black mb-2" style={{color:C.text}}>How candidates were shortlisted</div>
            <div className="text-xs mb-3 leading-relaxed" style={{color:C.muted}}>
              <span className="font-bold">{term.totalApplicants} residents applied.</span> Top {term.shortlistedTo} by <span className="font-bold" style={{color:C.purple}}>activity score</span> (events × 3 + posts) were shortlisted for voting.
            </div>
            {/* Applicant pool */}
            <div className="space-y-1.5">
              {EP2_POOL.map((p,i)=>(
                <div key={i} className="flex items-center gap-2 px-2 py-1.5 rounded-xl"
                  style={{background:p.shortlisted?"#fff":C.surface,border:`1px solid ${p.shortlisted?C.mint+"44":C.border}`}}>
                  <span className="text-xs w-5 text-center">{p.shortlisted?"✅":"❌"}</span>
                  <span className="text-xs font-bold flex-1" style={{color:p.shortlisted?C.text:C.muted}}>{p.name}</span>
                  <span className="text-xs" style={{color:C.muted}}>{p.eventsOrg}ev+{p.posts}p</span>
                  <span className="text-xs font-black px-1.5 py-0.5 rounded-full"
                    style={{background:p.shortlisted?C.mintL:C.surface,color:p.shortlisted?C.mint:C.muted}}>
                    {p.score}pts
                  </span>
                  {p.shortlisted&&<span className="text-xs font-black" style={{color:C.mint}}>#{i+1}</span>}
                </div>
              ))}
            </div>
            <div className="mt-2 text-xs px-2 py-1.5 rounded-xl font-medium" style={{background:C.purpleFg,color:C.purple}}>
              Score = (Events organised × 3) + Community posts
            </div>
          </div>
          <div className="px-4 py-2 flex items-center justify-between" style={{background:"#fff",borderTop:`1px solid ${C.border}`}}>
            <span className="text-xs font-bold" style={{color:C.muted}}>Voting period: {term.votingStart} → {term.votingEnd}</span>
            <span className="text-xs font-black" style={{color:C.coral}}>{totalVotes} votes cast</span>
          </div>
        </div>
      )}

      {/* ── CANDIDATES / VOTING CARDS ── */}
      {phase==="voting" && candidates.length>0 && (
        <div>
          <div className="flex items-center justify-between mb-3">
            <div className="font-black text-sm" style={{color:C.text}}>Shortlisted Candidates ({candidates.length}/4)</div>
            {voted&&<div className="text-xs font-bold px-2 py-0.5 rounded-full" style={{background:C.mintL,color:C.mint}}>✅ You voted</div>}
          </div>
          <div className="space-y-3">
            {candidates.map((c,i)=>{
              const myVote=voted===c.id;
              const vcount=c.votes+(myVote?1:0);
              const pct=totalVotes>0?Math.round(vcount/totalVotes*100):0;
              const rank=[...candidates].sort((a,b)=>b.votes-a.votes).findIndex(x=>x.id===c.id);
              const rankColors=[C.marigold,C.mint,C.purple,C.muted];
              return(
                <div key={c.id} className="rounded-2xl overflow-hidden"
                  style={{background:"#fff",border:`1.5px solid ${myVote?C.mint:C.border}`,boxShadow:myVote?`0 0 0 3px ${C.mint}22`:undefined}}>
                  <div className="h-1" style={{background:rankColors[rank]}}/>
                  <div className="px-4 pt-3 pb-3">
                    <div className="flex items-start gap-3">
                      <div className="relative flex-shrink-0">
                        <div className="w-12 h-12 rounded-xl flex items-center justify-center text-white font-black"
                          style={{background:c.color}}>{c.avatar}</div>
                        {rank===0&&<span className="absolute -top-1 -right-1 text-sm">👑</span>}
                      </div>
                      <div className="flex-1 min-w-0">
                        <div className="font-black text-sm" style={{color:C.text}}>{c.name}</div>
                        <div className="text-xs truncate" style={{color:C.muted}}>{c.apt}</div>
                        <div className="text-xs mt-0.5" style={{color:C.purple}}>{c.profession}</div>
                        <div className="flex gap-1.5 mt-1.5 flex-wrap">
                          <span className="text-xs px-2 py-0.5 rounded-full font-bold" style={{background:C.mintL,color:C.mint}}>✅ Verified</span>
                          <span className="text-xs px-2 py-0.5 rounded-full font-bold" style={{background:C.purpleFg,color:C.purple}}>📅 {c.eventsOrg} events</span>
                          <span className="text-xs px-2 py-0.5 rounded-full font-bold" style={{background:C.marigoldL,color:"#B87A00"}}>💬 {c.posts} posts</span>
                          <span className="text-xs px-2 py-0.5 rounded-full font-bold" style={{background:C.surface,color:C.muted}}>🏆 {calcScore(c.eventsOrg,c.posts)}pts</span>
                        </div>
                      </div>
                    </div>
                    <p className="text-xs mt-2 leading-relaxed px-1" style={{color:C.muted}}>"{c.statement}"</p>
                    <div className="mt-3">
                      <div className="flex items-center justify-between mb-1">
                        <span className="text-xs font-bold" style={{color:C.muted}}>{pct}% · {vcount} votes</span>
                        {rank===0&&<span className="text-xs font-black" style={{color:C.marigold}}>🏆 Leading</span>}
                      </div>
                      <div className="rounded-full h-2 mb-3" style={{background:C.border}}>
                        <div className="h-2 rounded-full transition-all duration-700"
                          style={{width:`${pct}%`,background:myVote?C.mint:c.color}}/>
                      </div>
                      {!voted&&meInArea?(
                        <button onClick={()=>doVote(c.id)} className="w-full py-2 rounded-xl font-black text-sm transition-all active:scale-95"
                          style={{background:voteAnim===c.id?C.mint:C.purple,color:"#fff"}}>
                          {voteAnim===c.id?"✅ Voted!":"🗳 Vote for "+c.name.split(" ")[0]}
                        </button>
                      ):myVote?(
                        <div className="w-full py-2 rounded-xl font-black text-sm text-center" style={{background:C.mintL,color:C.mint}}>✅ You voted for {c.name.split(" ")[0]}</div>
                      ):voted?(
                        <div className="w-full py-2 rounded-xl text-sm text-center font-medium" style={{background:C.surface,color:C.muted}}>Vote already cast</div>
                      ):(
                        <div className="w-full py-2 rounded-xl text-xs text-center font-medium" style={{background:C.surface,color:C.muted}}>Only {CM_AREAS.find(a=>a.id===selArea)?.label} residents can vote</div>
                      )}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* ── APPLY SECTION (pre_election or no_admin) ── */}
      {(phase==="pre_election"||phase==="no_admin") && meInArea && (
        <div className="rounded-2xl overflow-hidden" style={{border:`1.5px solid ${C.purple}33`}}>
          <div className="px-4 py-3" style={{background:C.purpleFg}}>
            <div className="font-black text-sm" style={{color:C.purple}}>✍️ Apply for Community Admin</div>
            <div className="text-xs mt-0.5" style={{color:C.muted}}>6-month term · Up to 4 shortlisted by activity · Area residents elect</div>
          </div>
          <div className="px-4 py-3" style={{background:"#fff"}}>
            <div className="space-y-2 mb-3">
              {[
                [MY_STATS.verified,        "Verified Resident",                    "Government ID + address proof required"],
                [MY_STATS.eventsOrg>=5,    `5+ Events Organised (${MY_STATS.eventsOrg})`, "Min 5 community events organised"],
                [MY_STATS.posts>=10,       `Active Poster (${MY_STATS.posts} posts)`,       "Min 10 posts in community feed"],
                [candidates.length<4,      `Slot Available (${candidates.length}/4)`,        "Max 4 candidates shortlisted"],
              ].map(([ok,label,sub])=>(
                <div key={label} className="flex items-start gap-2.5">
                  <span className="text-sm mt-0.5 flex-shrink-0">{ok?"✅":"❌"}</span>
                  <div><div className="text-xs font-bold" style={{color:ok?C.text:C.muted}}>{label}</div>
                       <div className="text-xs" style={{color:C.muted}}>{sub}</div></div>
                </div>
              ))}
            </div>
            <button onClick={handleApplyClick}
              className="w-full py-2.5 rounded-xl font-black text-sm transition-all active:scale-95"
              style={{background:C.purple,color:"#fff",cursor:"pointer"}}>
              {meEligible ? "Apply to Stand for Election →" : "Check My Eligibility →"}
            </button>
          </div>
        </div>
      )}

      {/* Stable phase — next election info */}
      {phase==="stable" && (
        <div className="rounded-2xl px-4 py-3" style={{background:C.surface,border:`1.5px solid ${C.border}`}}>
          <div className="font-black text-xs mb-1" style={{color:C.muted}}>NEXT ELECTION</div>
          <div className="text-sm" style={{color:C.text}}>Applications will open <span className="font-black" style={{color:C.marigold}}>{term.nextElectionOpen}</span></div>
          <div className="text-xs mt-0.5" style={{color:C.muted}}>All members will be notified 1 month before the election. Eligible residents can then apply to stand.</div>
        </div>
      )}

      <div className="h-4"/>
    </div>
  );
}

// ─── CM Apply Screen ─────────────────────────────────────────────────────────
function CMApplyScreen({step, setStep, form, setForm, onDone, onBack, area}){
  const set=(k,v)=>setForm(f=>({...f,[k]:v}));
  const STEPS=["Eligibility","Your Details","Submit"];
  return(
    <div className="px-4 py-4">
      {/* Back */}
      <button onClick={onBack} className="flex items-center gap-1 text-sm font-bold mb-4" style={{color:C.purple}}>
        ← Back to Elections
      </button>
      <h2 className="text-lg font-black mb-1" style={{color:C.text}}>Apply as Community Manager</h2>
      <p className="text-xs mb-4" style={{color:C.muted}}>Area: <span className="font-bold" style={{color:C.purple}}>{area?.label}</span></p>

      {/* Step dots */}
      <div className="flex items-center gap-2 mb-6">
        {STEPS.map((s,i)=>(
          <div key={s} className="flex items-center gap-2">
            <div className="flex flex-col items-center">
              <div className="w-7 h-7 rounded-full flex items-center justify-center font-black text-xs"
                style={{background:i+1<=step?C.purple:"#E5E5E5",color:i+1<=step?"#fff":C.muted}}>
                {i+1<step?"✓":i+1}
              </div>
              <div className="text-xs mt-1 font-semibold" style={{color:i+1===step?C.purple:C.muted}}>{s}</div>
            </div>
            {i<STEPS.length-1&&<div className="w-10 h-0.5 mb-4" style={{background:i+1<step?C.purple:C.border}}/>}
          </div>
        ))}
      </div>

      {step===1&&(
        <div className="space-y-3">
          <div className="rounded-2xl p-4" style={{background:"#fff",border:`1.5px solid ${C.border}`}}>
            <div className="font-black text-sm mb-3" style={{color:C.text}}>Eligibility Requirements</div>
            {[
              ["✅","Verified Resident","Government ID & address proof verified"],
              ["✅","5+ Events Organised","You've organised 7 community events"],
              ["✅","Active Community Member","24 posts in community feed"],
              ["✅","Voting Rights","You are a verified area resident"],
            ].map(([ic,t,s])=>(
              <div key={t} className="flex items-start gap-3 mb-3">
                <span className="text-base flex-shrink-0">{ic}</span>
                <div>
                  <div className="text-sm font-bold" style={{color:C.text}}>{t}</div>
                  <div className="text-xs" style={{color:C.muted}}>{s}</div>
                </div>
              </div>
            ))}
          </div>
          <div className="rounded-2xl p-3 text-xs" style={{background:C.purpleFg,color:C.purple}}>
            ⚠️ By applying, your name and details will be visible to all residents of {area?.label}.
            The community will vote within the election period.
          </div>
          <button onClick={()=>setStep(2)} className="w-full py-3 rounded-xl font-black text-sm"
            style={{background:C.purple,color:"#fff"}}>I Understand · Continue →</button>
        </div>
      )}

      {step===2&&(
        <div className="space-y-4">
          {/* Photo upload */}
          <div>
            <label className="text-sm font-black block mb-1.5" style={{color:C.text}}>📸 Your Photo</label>
            <div className="rounded-2xl border-2 border-dashed flex flex-col items-center justify-center py-8 cursor-pointer"
              style={{borderColor:form.photo?C.mint:C.border,background:form.photo?C.mintL:C.surface}}
              onClick={()=>set("photo","uploaded")}>
              {form.photo
                ?<><span className="text-3xl">✅</span><span className="text-xs font-bold mt-1" style={{color:C.mint}}>Photo uploaded</span></>
                :<><span className="text-3xl">📷</span><span className="text-xs font-bold mt-1" style={{color:C.muted}}>Tap to upload a clear face photo</span></>
              }
            </div>
          </div>
          {/* Address proof */}
          <div>
            <label className="text-sm font-black block mb-1.5" style={{color:C.text}}>📄 Recent Address Proof</label>
            <div className="rounded-2xl border-2 border-dashed flex flex-col items-center justify-center py-6 cursor-pointer"
              style={{borderColor:form.proof?C.mint:C.border,background:form.proof?C.mintL:C.surface}}
              onClick={()=>set("proof","uploaded")}>
              {form.proof
                ?<><span className="text-3xl">✅</span><span className="text-xs font-bold mt-1" style={{color:C.mint}}>Document uploaded</span></>
                :<><span className="text-3xl">🗂</span><span className="text-xs font-bold mt-1" style={{color:C.muted}}>Electricity bill / Bank statement (≤3 months)</span></>
              }
            </div>
          </div>
          {/* Profession */}
          <div>
            <label className="text-sm font-black block mb-1.5" style={{color:C.text}}>💼 Profession / Background</label>
            <input value={form.profession} onChange={e=>set("profession",e.target.value)}
              placeholder="e.g. Software Engineer at Wipro, EC Phase 2"
              className="w-full rounded-xl px-4 py-3 text-sm focus:outline-none"
              style={{border:`2px solid ${form.profession?C.mint:C.border}`,background:"#fff",color:C.text}}/>
          </div>
          {/* Statement */}
          <div>
            <label className="text-sm font-black block mb-1.5" style={{color:C.text}}>🗣 Your Statement <span style={{color:C.muted,fontWeight:400}}>(max 200 chars)</span></label>
            <textarea value={form.statement} onChange={e=>set("statement",e.target.value.slice(0,200))}
              placeholder="Why do you want to be Community Manager? What will you do for the area?"
              rows={3}
              className="w-full rounded-xl px-4 py-3 text-sm focus:outline-none resize-none"
              style={{border:`2px solid ${form.statement?C.mint:C.border}`,background:"#fff",color:C.text}}/>
            <div className="text-xs text-right mt-0.5" style={{color:C.muted}}>{form.statement.length}/200</div>
          </div>
          <div className="flex gap-3">
            <button onClick={()=>setStep(1)} className="flex-1 py-3 rounded-xl font-bold text-sm"
              style={{background:C.surface,color:C.muted,border:`1.5px solid ${C.border}`}}>← Back</button>
            <button onClick={()=>{if(form.photo&&form.proof&&form.profession&&form.statement)setStep(3);}}
              className="flex-1 py-3 rounded-xl font-black text-sm"
              style={{background:form.photo&&form.proof&&form.profession&&form.statement?C.purple:C.border,
                      color:form.photo&&form.proof&&form.profession&&form.statement?"#fff":C.muted}}>
              Review →
            </button>
          </div>
        </div>
      )}

      {step===3&&(
        <div className="space-y-3">
          <div className="rounded-2xl overflow-hidden" style={{background:"#fff",border:`1.5px solid ${C.border}`}}>
            <div className="px-4 py-2 font-black text-xs" style={{background:C.purpleFg,color:C.purple}}>Review Your Application</div>
            {[["📸 Photo","Uploaded ✅"],["📄 Address Proof","Uploaded ✅"],["💼 Profession",form.profession],["🗣 Statement",form.statement]].map(([l,v])=>(
              <div key={l} className="px-4 py-2.5" style={{borderBottom:`1px solid ${C.border}`}}>
                <div className="text-xs font-bold mb-0.5" style={{color:C.muted}}>{l}</div>
                <div className="text-sm" style={{color:C.text}}>{v}</div>
              </div>
            ))}
            <div className="px-4 py-2.5">
              <div className="text-xs font-bold mb-0.5" style={{color:C.muted}}>📍 Area</div>
              <div className="text-sm" style={{color:C.text}}>{area?.label}</div>
            </div>
          </div>
          <div className="rounded-2xl p-3 text-xs" style={{background:C.mintL,color:C.mint}}>
            ✅ Your application will be reviewed by the MyTown 360 team within 24 hours.
            Once approved, residents of {area?.label} will be able to vote for you.
          </div>
          <div className="flex gap-3">
            <button onClick={()=>setStep(2)} className="flex-1 py-3 rounded-xl font-bold text-sm"
              style={{background:C.surface,color:C.muted,border:`1.5px solid ${C.border}`}}>← Edit</button>
            <button onClick={onDone} className="flex-1 py-3 rounded-xl font-black text-sm"
              style={{background:C.mint,color:"#fff"}}>Submit Application 🎉</button>
          </div>
        </div>
      )}
    </div>
  );
}

// ─── CM Success Screen ───────────────────────────────────────────────────────
function CMSuccessScreen({onBack}){
  return(
    <div className="px-4 py-12 flex flex-col items-center text-center">
      <div className="text-6xl mb-4">🎉</div>
      <h2 className="text-2xl font-black mb-2" style={{color:C.text}}>Application Submitted!</h2>
      <p className="text-sm mb-1" style={{color:C.muted}}>Your candidacy application has been received.</p>
      <p className="text-xs mb-6" style={{color:C.muted}}>Our team will review it within 24 hours. You'll get a notification once it's approved and residents can start voting for you.</p>
      <div className="w-full rounded-2xl p-4 mb-6 space-y-2" style={{background:C.purpleFg,border:`1.5px solid ${C.purple}22`}}>
        {[["📬","Notification","You'll be notified on approval"],["🗳","Voting Opens","Area residents can vote once approved"],["👑","Result","Candidate with most votes becomes manager"]].map(([ic,t,s])=>(
          <div key={t} className="flex items-center gap-3 text-left">
            <span className="text-xl">{ic}</span>
            <div><div className="text-sm font-bold" style={{color:C.purple}}>{t}</div><div className="text-xs" style={{color:C.muted}}>{s}</div></div>
          </div>
        ))}
      </div>
      <button onClick={onBack} className="w-full py-3 rounded-xl font-black text-sm"
        style={{background:C.purple,color:"#fff"}}>Back to Elections →</button>
    </div>
  );
}

// ─── Admin Directory Screen ──────────────────────────────────────────────────
function AdminDirectoryScreen({nav}){
  const [msgTarget,setMsgTarget]=useState(null);
  const [msgText,setMsgText]=useState("");
  const [sent,setSent]=useState(null);
  const sendMsg=()=>{ if(!msgText.trim())return; setSent(msgTarget); setMsgTarget(null); setMsgText(""); };
  return(
    <div className="px-4 py-4">
      <button onClick={()=>nav("messages")} className="flex items-center gap-1 text-sm font-bold mb-4" style={{color:C.purple}}>← Back</button>
      <h2 className="text-xl font-black mb-1" style={{color:C.text}}>Community Admins Directory</h2>
      <p className="text-xs mb-4" style={{color:C.muted}}>As a <span className="font-bold" style={{color:C.mint}}>verified resident</span>, you can contact any area's Community Admin for information and assistance.</p>

      {/* Message compose modal */}
      {msgTarget&&(
        <div style={{position:"fixed",inset:0,zIndex:100,display:"flex",alignItems:"flex-end",justifyContent:"center",background:"rgba(26,16,51,0.55)",backdropFilter:"blur(4px)"}}>
          <div style={{width:"100%",maxWidth:430,background:"#fff",borderRadius:"24px 24px 0 0",padding:"0 20px 36px"}}>
            <div style={{display:"flex",justifyContent:"center",paddingTop:12,paddingBottom:8}}><div style={{width:40,height:4,borderRadius:99,background:C.border}}/></div>
            <div style={{fontWeight:900,fontSize:15,color:C.text,marginBottom:4}}>Message {msgTarget.name}</div>
            <div style={{fontSize:12,color:C.muted,marginBottom:12}}>{CM_AREAS.find(a=>a.id===msgTarget.area)?.label} · Community Admin</div>
            <PIITextarea value={msgText} onChange={setMsgText} placeholder={`Write your message to ${msgTarget.name.split(" ")[0]}…`} rows={4}/>
            <div style={{marginTop:12,display:"flex",gap:10}}>
              <button onClick={()=>{setMsgTarget(null);setMsgText("");}} style={{flex:1,padding:"11px",borderRadius:14,background:C.surface,color:C.muted,fontWeight:700,fontSize:13,border:`1.5px solid ${C.border}`,cursor:"pointer"}}>Cancel</button>
              <button onClick={sendMsg} style={{flex:1,padding:"11px",borderRadius:14,background:msgText.trim()?C.purple:C.border,color:msgText.trim()?"#fff":C.muted,fontWeight:900,fontSize:13,border:"none",cursor:"pointer"}}>Send Message ↑</button>
            </div>
          </div>
        </div>
      )}

      {/* Sent success toast */}
      {sent&&(
        <div className="mb-4 px-4 py-3 rounded-2xl flex items-center gap-2" style={{background:C.mintL,border:`1.5px solid ${C.mint}44`}}>
          <span className="text-lg">✅</span>
          <div>
            <div className="font-bold text-sm" style={{color:C.mint}}>Message sent to {sent.name}</div>
            <div className="text-xs" style={{color:C.muted}}>They'll respond in your Messages tab</div>
          </div>
        </div>
      )}

      <div className="space-y-3 pb-24">
        {CM_AREAS.map(area=>{
          const mgr=CURRENT_MANAGERS[area.id];
          const phase=ELECTION_PHASES[area.id];
          return(
            <div key={area.id} className="rounded-2xl overflow-hidden" style={{background:"#fff",border:`1.5px solid ${C.border}`}}>
              {/* Area header */}
              <div className="px-4 py-2 flex items-center justify-between" style={{background:C.surface,borderBottom:`1.5px solid ${C.border}`}}>
                <div className="font-black text-sm" style={{color:C.text}}>{area.label}</div>
                <span className="text-xs font-bold px-2 py-0.5 rounded-full"
                  style={{background:mgr?C.mintL:C.marigoldL, color:mgr?C.mint:"#B87A00"}}>
                  {mgr?"✅ Admin Active":"🏛 Vacant"}
                </span>
              </div>
              {mgr?(
                <div className="px-4 py-3">
                  <div className="flex items-center gap-3 mb-3">
                    <div className="w-12 h-12 rounded-xl flex items-center justify-center text-white font-black flex-shrink-0"
                      style={{background:mgr.color}}>{mgr.avatar}</div>
                    <div className="flex-1">
                      <div className="font-black text-sm" style={{color:C.text}}>{mgr.name}</div>
                      <div className="text-xs" style={{color:C.muted}}>{mgr.apt}</div>
                      <div className="flex gap-1.5 mt-1 flex-wrap">
                        <span className="text-xs px-2 py-0.5 rounded-full font-bold" style={{background:C.mintL,color:C.mint}}>✅ Verified Admin</span>
                        <span className="text-xs px-2 py-0.5 rounded-full font-bold" style={{background:C.purpleFg,color:C.purple}}>📅 {mgr.events} events</span>
                      </div>
                    </div>
                  </div>
                  <button onClick={()=>setMsgTarget({...mgr,area:area.id})}
                    className="w-full py-2.5 rounded-xl font-black text-sm transition-all active:scale-95"
                    style={{background:C.purple,color:"#fff"}}>
                    📩 Send Message to {mgr.name.split(" ")[0]}
                  </button>
                </div>
              ):(
                <div className="px-4 py-4 text-center">
                  <div className="text-2xl mb-1">🏛</div>
                  <div className="text-sm font-bold" style={{color:C.muted}}>No admin elected yet</div>
                  <div className="text-xs mt-0.5" style={{color:C.muted}}>
                    {phase==="voting"?"Election is in progress — results coming soon":
                     phase==="pre_election"?"Election nominations are open":
                     "Election will open soon"}
                  </div>
                  <button onClick={()=>nav("community")} className="mt-3 px-4 py-1.5 rounded-xl text-xs font-bold"
                    style={{background:C.purpleFg,color:C.purple}}>View Election →</button>
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ─── Event Create Screen ──────────────────────────────────────────────────────
function EventCreateScreen({onBack}){
  const [step,setStep]=useState(1);
  const [form,setForm]=useState({title:"",desc:"",date:"",time:"",category:"",location:"",useGPS:false,photos:[],invitees:[]});
  const [blocked,setBlocked]=useState(false);
  const [done,setDone]=useState(false);
  const set=(k,v)=>setForm(f=>({...f,[k]:v}));
  const CATEGORIES=["🎉 Social","📚 Education","🏃 Sports & Fitness","🎨 Art & Culture","🌿 Environment","🍽 Food & Dining","👶 Kids & Family","🛡 Safety"];
  const STEPS=["Details","Location","Invite","Photos"];

  const handleDescChange=(v)=>{
    set("desc",v);
    if(checkViolation(v)) setBlocked(true); else setBlocked(false);
  };

  if(done) return(
    <div className="px-4 py-12 flex flex-col items-center text-center">
      <div className="text-6xl mb-4">🎉</div>
      <h2 className="text-2xl font-black mb-2" style={{color:C.text}}>Event Created!</h2>
      <p className="text-sm mb-6" style={{color:C.muted}}>Your event has been posted to the community. Invited members will be notified.</p>
      <button onClick={onBack} className="w-full max-w-xs py-3 rounded-xl font-black text-sm" style={{background:C.purple,color:"#fff"}}>Back to Events →</button>
    </div>
  );

  return(
    <div className="px-4 py-4">
      <button onClick={onBack} className="flex items-center gap-1 text-sm font-bold mb-4" style={{color:C.purple}}>← Cancel</button>
      <h2 className="text-lg font-black mb-1" style={{color:C.text}}>Host a Community Event</h2>

      {/* Step indicators */}
      <div className="flex items-center gap-1.5 mb-5">
        {STEPS.map((s,i)=>(
          <div key={s} className="flex items-center gap-1.5">
            <div className="flex flex-col items-center">
              <div className="w-7 h-7 rounded-full flex items-center justify-center font-black text-xs"
                style={{background:i+1<=step?C.purple:"#E5E5E5",color:i+1<=step?"#fff":C.muted}}>
                {i+1<step?"✓":i+1}
              </div>
              <div className="text-xs mt-0.5 font-semibold" style={{color:i+1===step?C.purple:C.muted,fontSize:9}}>{s}</div>
            </div>
            {i<STEPS.length-1&&<div className="w-6 h-0.5 mb-3" style={{background:i+1<step?C.purple:C.border}}/>}
          </div>
        ))}
      </div>

      {/* Step 1: Event Details */}
      {step===1&&(
        <div className="space-y-4">
          <div>
            <label className="text-sm font-black block mb-1.5" style={{color:C.text}}>Event Title *</label>
            <PIIInput value={form.title} onChange={v=>set("title",v)} placeholder="e.g. Weekend Yoga at Prestige Garden"/>
          </div>
          <div>
            <label className="text-sm font-black block mb-1.5" style={{color:C.text}}>Description</label>
            {blocked&&<ContentBlockedBanner context="event description" onEdit={()=>setBlocked(false)}/>}
            {!blocked&&<PIITextarea value={form.desc} onChange={handleDescChange} placeholder="Tell the community about this event…" rows={3}/>}
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="text-sm font-black block mb-1.5" style={{color:C.text}}>📅 Date *</label>
              <input type="date" value={form.date} onChange={e=>set("date",e.target.value)}
                className="w-full rounded-xl px-3 py-2.5 text-sm focus:outline-none"
                style={{border:`2px solid ${C.border}`,background:"#fff",color:C.text}}/>
            </div>
            <div>
              <label className="text-sm font-black block mb-1.5" style={{color:C.text}}>⏰ Time *</label>
              <input type="time" value={form.time} onChange={e=>set("time",e.target.value)}
                className="w-full rounded-xl px-3 py-2.5 text-sm focus:outline-none"
                style={{border:`2px solid ${C.border}`,background:"#fff",color:C.text}}/>
            </div>
          </div>
          <div>
            <label className="text-sm font-black block mb-1.5" style={{color:C.text}}>Category *</label>
            <div className="grid grid-cols-2 gap-2">
              {CATEGORIES.map(cat=>(
                <button key={cat} onClick={()=>set("category",cat)}
                  className="py-2 px-3 rounded-xl text-xs font-bold border-2 text-left transition-all"
                  style={form.category===cat?{borderColor:C.purple,background:C.purpleFg,color:C.purple}:{borderColor:C.border,color:C.muted,background:"#fff"}}>
                  {cat}
                </button>
              ))}
            </div>
          </div>
          <button onClick={()=>{if(form.title&&form.date&&form.category&&!blocked)setStep(2);}}
            className="w-full py-3 rounded-xl font-black text-sm transition-all"
            style={{background:form.title&&form.date&&form.category&&!blocked?C.purple:C.border, color:form.title&&form.date&&form.category&&!blocked?"#fff":C.muted}}>
            Next: Location →
          </button>
        </div>
      )}

      {/* Step 2: Location */}
      {step===2&&(
        <div className="space-y-4">
          <div>
            <label className="text-sm font-black block mb-1.5" style={{color:C.text}}>📍 Event Location *</label>
            <div className="flex items-center rounded-xl px-3 py-2.5 gap-2"
              style={{background:"#fff",border:`2px solid ${form.useGPS?C.mint:C.border}`}}>
              <span className="text-base">📍</span>
              <input className="flex-1 text-sm font-medium bg-transparent focus:outline-none" style={{color:C.text}}
                placeholder="e.g. Prestige Sunrise Park Clubhouse, EC Phase 1"
                value={form.location} onChange={e=>set("location",e.target.value)} disabled={form.useGPS}/>
            </div>
          </div>
          <button onClick={()=>{set("useGPS",!form.useGPS);if(!form.useGPS)set("location","📍 Electronic City Phase 2 (12.8456°N, 77.6603°E)");else set("location","");}}
            className="w-full py-2.5 rounded-xl font-bold text-sm flex items-center justify-center gap-2 transition-all"
            style={{background:form.useGPS?C.mintL:C.surface,border:`1.5px solid ${form.useGPS?C.mint:C.border}`,color:form.useGPS?C.mint:C.muted}}>
            {form.useGPS?"✅ Using your current location":"📡 Use My Current GPS Location"}
          </button>
          {form.useGPS&&(
            <div className="rounded-xl px-4 py-3" style={{background:C.mintL,border:`1.5px solid ${C.mint}44`}}>
              <div className="text-xs font-bold" style={{color:C.mint}}>📍 Location Shared</div>
              <div className="text-xs mt-0.5" style={{color:C.muted}}>EC Phase 2 · 12.8456°N, 77.6603°E · Accurate to 10m</div>
            </div>
          )}
          {/* Mini map preview */}
          <div className="rounded-2xl overflow-hidden" style={{border:`1.5px solid ${C.border}`,height:140,background:"#E8E3F5",position:"relative"}}>
            <svg width="100%" height="100%">
              <rect width="100%" height="100%" fill="#E8E3F5"/>
              <rect x="20%" y="30%" width="60%" height="40%" rx="8" fill="#D4C8E8"/>
              <circle cx="50%" cy="50%" r="8" fill={C.coral}/>
              <circle cx="50%" cy="50%" r="20" fill={C.coral} fillOpacity="0.2"/>
            </svg>
            <div className="absolute bottom-2 left-2 right-2 rounded-xl px-3 py-1.5 text-xs font-semibold" style={{background:"rgba(255,255,255,0.9)",color:C.text}}>
              📍 {form.location||"Enter location above"}
            </div>
          </div>
          <div className="flex gap-3">
            <button onClick={()=>setStep(1)} className="flex-1 py-3 rounded-xl font-bold text-sm" style={{background:C.surface,color:C.muted,border:`1.5px solid ${C.border}`}}>← Back</button>
            <button onClick={()=>{if(form.location)setStep(3);}} className="flex-1 py-3 rounded-xl font-black text-sm"
              style={{background:form.location?C.purple:C.border,color:form.location?"#fff":C.muted}}>Next: Invite →</button>
          </div>
        </div>
      )}

      {/* Step 3: Invite Members */}
      {step===3&&(
        <div className="space-y-3">
          <div className="text-xs px-3 py-2 rounded-xl font-medium" style={{background:C.purpleFg,color:C.purple}}>
            {form.invitees.length===0?"Tap members to invite them to this event":
             `${form.invitees.length} member${form.invitees.length>1?"s":""} invited`}
          </div>
          <div className="space-y-2">
            {COMMUNITY_MEMBERS.map(m=>{
              const sel=form.invitees.includes(m.id);
              return(
                <button key={m.id} onClick={()=>set("invitees",sel?form.invitees.filter(x=>x!==m.id):[...form.invitees,m.id])}
                  className="w-full flex items-center gap-3 px-4 py-3 rounded-2xl text-left transition-all"
                  style={{background:sel?C.purpleFg:"#fff",border:`1.5px solid ${sel?C.purple:C.border}`}}>
                  <div className="w-10 h-10 rounded-xl flex items-center justify-center text-white font-black text-xs flex-shrink-0"
                    style={{background:m.avC}}>{m.av}</div>
                  <div className="flex-1">
                    <div className="font-bold text-sm" style={{color:sel?C.purple:C.text}}>{m.name}</div>
                    <div className="text-xs" style={{color:C.muted}}>{m.apt}</div>
                  </div>
                  <div className="w-6 h-6 rounded-full flex items-center justify-center flex-shrink-0"
                    style={{background:sel?C.purple:C.surface,border:`1.5px solid ${sel?C.purple:C.border}`}}>
                    {sel&&<span className="text-white text-xs font-black">✓</span>}
                  </div>
                </button>
              );
            })}
          </div>
          <div className="flex gap-3">
            <button onClick={()=>setStep(2)} className="flex-1 py-3 rounded-xl font-bold text-sm" style={{background:C.surface,color:C.muted,border:`1.5px solid ${C.border}`}}>← Back</button>
            <button onClick={()=>setStep(4)} className="flex-1 py-3 rounded-xl font-black text-sm" style={{background:C.purple,color:"#fff"}}>
              {form.invitees.length>0?`Next: Photos (${form.invitees.length} invited) →`:"Next: Photos →"}
            </button>
          </div>
        </div>
      )}

      {/* Step 4: Photos */}
      {step===4&&(
        <div className="space-y-4">
          <div className="text-xs px-3 py-2 rounded-xl font-medium" style={{background:C.purpleFg,color:C.purple}}>
            📸 Add photos to make your event more engaging. All uploads are screened for inappropriate content.
          </div>
          {/* Upload area */}
          <button onClick={()=>set("photos",[...form.photos,`photo_${form.photos.length+1}`])}
            className="w-full py-8 rounded-2xl border-2 border-dashed flex flex-col items-center justify-center gap-2 transition-all"
            style={{borderColor:form.photos.length>0?C.mint:C.border,background:C.surface}}>
            <span className="text-4xl">{form.photos.length>0?"📸":"🖼"}</span>
            <span className="text-sm font-bold" style={{color:C.muted}}>
              {form.photos.length>0?`${form.photos.length} photo${form.photos.length>1?"s":""} added · Tap to add more`:"Tap to upload event photos"}
            </span>
          </button>
          {form.photos.length>0&&(
            <div className="grid grid-cols-3 gap-2">
              {form.photos.map((_,i)=>(
                <div key={i} className="rounded-xl aspect-square flex items-center justify-center text-3xl"
                  style={{background:C.purpleFg}}>📷</div>
              ))}
            </div>
          )}
          {/* Content policy notice */}
          <div className="rounded-xl px-3 py-2.5 text-xs" style={{background:"#FFF8E7",border:`1.5px solid ${C.marigold}55`}}>
            <span className="font-bold" style={{color:"#B87A00"}}>🛡 Content Policy: </span>
            <span style={{color:C.muted}}>All photos are automatically scanned for sexual, violent or inappropriate content and will be blocked if they violate our Community Guidelines.</span>
          </div>
          {/* Summary */}
          <div className="rounded-2xl overflow-hidden" style={{background:"#fff",border:`1.5px solid ${C.border}`}}>
            <div className="px-4 py-2 font-black text-xs" style={{background:C.purpleFg,color:C.purple}}>Event Summary</div>
            {[["📌",form.title],["📅",`${form.date} at ${form.time}`],["📍",form.location],[`${form.category.split(" ")[0]}`,form.category.slice(3)],[`👥`,`${form.invitees.length} members invited`],[`📸`,`${form.photos.length} photos`]].map(([ic,val])=>(
              <div key={ic} className="px-4 py-2.5 flex items-center gap-2" style={{borderBottom:`1px solid ${C.border}`}}>
                <span className="text-sm">{ic}</span><span className="text-sm" style={{color:C.text}}>{val}</span>
              </div>
            ))}
          </div>
          <div className="flex gap-3">
            <button onClick={()=>setStep(3)} className="flex-1 py-3 rounded-xl font-bold text-sm" style={{background:C.surface,color:C.muted,border:`1.5px solid ${C.border}`}}>← Back</button>
            <button onClick={()=>setDone(true)} className="flex-1 py-3 rounded-xl font-black text-sm" style={{background:C.mint,color:"#fff"}}>🎉 Post Event</button>
          </div>
        </div>
      )}
    </div>
  );
}

// ─── SCREEN: Helplines ────────────────────────────────────────────────────────
function HelplineScreen({nav}){
  const cats = [...new Set(HELPLINES.map(h=>h.cat))];
  const [expandedCat, setExpandedCat] = useState(null);

  const catMeta = {
    "Emergency":  { icon:"🚨", color:"#DC2626", bg:"#FEF2F2" },
    "EC Local":   { icon:"🏘", color:"#1D4ED8", bg:"#EFF6FF" },
    "Utilities":  { icon:"⚡", color:"#D97706", bg:"#FFFBEB" },
    "Transport":  { icon:"🚌", color:"#0369A1", bg:"#F0F9FF" },
    "Medical":    { icon:"🏥", color:"#059669", bg:"#F0FDF4" },
    "Police":     { icon:"👮", color:"#1E40AF", bg:"#EFF6FF" },
  };

  // Emergency numbers always shown at top
  const emergencyNums = HELPLINES.filter(h=>h.cat==="Emergency");

  return(
    <div style={{minHeight:"100vh",background:C.surface,paddingBottom:80}}>
      {/* Back header */}
      <div style={{display:"flex",alignItems:"center",gap:10,padding:"16px 16px 12px",background:"#fff",borderBottom:`1.5px solid ${C.border}`,position:"sticky",top:0,zIndex:10}}>
        <button onClick={()=>nav("feed")}
          style={{width:36,height:36,borderRadius:10,background:C.purpleFg,border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",color:C.purple,fontSize:18,fontWeight:900,flexShrink:0}}>
          ‹
        </button>
        <div>
          <div style={{fontWeight:900,fontSize:16,color:C.text}}>📞 Helpline Numbers</div>
          <div style={{fontSize:11,color:C.muted}}>Electronic City · Bangalore</div>
        </div>
      </div>

      <div style={{padding:"14px 14px 0"}}>
        {/* Emergency strip — always visible */}
        <div style={{borderRadius:16,background:"#FEF2F2",border:"1.5px solid #FCA5A5",padding:"12px 12px 6px",marginBottom:14}}>
          <div style={{display:"flex",alignItems:"center",gap:6,marginBottom:10}}>
            <span style={{fontSize:16}}>🚨</span>
            <span style={{fontWeight:900,fontSize:13,color:"#DC2626",textTransform:"uppercase",letterSpacing:"0.08em"}}>Emergency Numbers</span>
          </div>
          <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:7}}>
            {emergencyNums.map(h=>(
              <a key={h.phone} href={`tel:${h.phone}`}
                style={{display:"flex",alignItems:"center",gap:8,padding:"10px 10px",borderRadius:12,background:"#fff",border:"1.5px solid #FCA5A5",textDecoration:"none",cursor:"pointer"}}>
                <div style={{width:32,height:32,borderRadius:8,background:h.color,display:"flex",alignItems:"center",justifyContent:"center",fontSize:14,flexShrink:0}}>
                  {h.icon}
                </div>
                <div style={{flex:1,minWidth:0}}>
                  <div style={{fontSize:11,fontWeight:700,color:"#1F2937",lineHeight:1.2,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}}>{h.name}</div>
                  <div style={{fontSize:13,fontWeight:900,color:h.color,letterSpacing:"0.03em"}}>{h.phone}</div>
                </div>
              </a>
            ))}
          </div>
        </div>

        {/* Other category accordions */}
        {cats.filter(c=>c!=="Emergency").map(cat=>{
          const meta = catMeta[cat]||{icon:"📋",color:C.purple,bg:C.purpleFg};
          const items = HELPLINES.filter(h=>h.cat===cat);
          const isOpen = expandedCat===cat;
          return(
            <div key={cat} style={{borderRadius:14,background:"#fff",border:`1.5px solid ${C.border}`,marginBottom:10,overflow:"hidden"}}>
              {/* Category header */}
              <button onClick={()=>setExpandedCat(isOpen?null:cat)}
                style={{width:"100%",display:"flex",alignItems:"center",gap:10,padding:"13px 14px",background:isOpen?meta.bg:"#fff",border:"none",cursor:"pointer",textAlign:"left"}}>
                <div style={{width:36,height:36,borderRadius:10,background:meta.bg,border:`1.5px solid ${meta.color}33`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:18,flexShrink:0}}>
                  {meta.icon}
                </div>
                <div style={{flex:1}}>
                  <div style={{fontWeight:800,fontSize:14,color:meta.color}}>{cat}</div>
                  <div style={{fontSize:11,color:C.muted}}>{items.length} contact{items.length>1?"s":""}</div>
                </div>
                <span style={{fontSize:16,color:C.muted,fontWeight:700,transform:isOpen?"rotate(90deg)":"none",transition:"transform 0.2s",flexShrink:0}}>›</span>
              </button>

              {/* Expanded items */}
              {isOpen && (
                <div style={{borderTop:`1px solid ${C.border}`,padding:"10px 12px 12px",display:"flex",flexDirection:"column",gap:7}}>
                  {items.map(h=>(
                    <a key={h.phone} href={`tel:${h.phone}`}
                      style={{display:"flex",alignItems:"center",gap:10,padding:"10px 12px",borderRadius:12,background:meta.bg,border:`1.5px solid ${meta.color}33`,textDecoration:"none"}}>
                      <div style={{width:36,height:36,borderRadius:9,background:"#fff",border:`1.5px solid ${meta.color}44`,display:"flex",alignItems:"center",justifyContent:"center",fontSize:18,flexShrink:0}}>
                        {h.icon}
                      </div>
                      <div style={{flex:1,minWidth:0}}>
                        <div style={{fontSize:12,fontWeight:700,color:"#1F2937",marginBottom:1,lineHeight:1.2}}>{h.name}</div>
                        <div style={{fontSize:14,fontWeight:900,color:meta.color,letterSpacing:"0.03em"}}>{h.phone}</div>
                      </div>
                      <div style={{width:32,height:32,borderRadius:8,background:meta.color,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0}}>
                        <span style={{fontSize:14}}>📞</span>
                      </div>
                    </a>
                  ))}
                </div>
              )}
            </div>
          );
        })}

        {/* BMTC / KSRTC note */}
        <div style={{borderRadius:14,background:"#F0F9FF",border:"1.5px solid #BAE6FD",padding:"12px 14px",marginBottom:10}}>
          <div style={{fontWeight:800,fontSize:13,color:"#0369A1",marginBottom:6}}>🚌 Bus Routes serving Electronic City</div>
          <div style={{display:"flex",flexWrap:"wrap",gap:6}}>
            {BUS_ROUTES.map(r=>(
              <span key={r} style={{padding:"4px 10px",borderRadius:99,background:"#fff",border:"1.5px solid #BAE6FD",fontSize:11,fontWeight:700,color:"#0369A1"}}>{r}</span>
            ))}
          </div>
        </div>

        {/* Disclaimer */}
        <div style={{textAlign:"center",padding:"8px 0 4px"}}>
          <span style={{fontSize:11,color:C.muted}}>Tap any card to call directly · Numbers verified for EC Bangalore</span>
        </div>
      </div>
    </div>
  );
}

// ─── Admin Panel Screen ───────────────────────────────────────────────────────
function AdminPanelScreen({nav}){
  const TABS=[
    {id:"overview",   icon:"📊", label:"Overview"},
    {id:"otp",        icon:"🔑", label:"OTP"},
    {id:"email",      icon:"✉️",  label:"Email"},
    {id:"notif",      icon:"🔔", label:"Notifications"},
    {id:"integrations",icon:"🔌",label:"Integrations"},
    {id:"users",      icon:"👥", label:"Users"},
    {id:"reports",    icon:"🚩", label:"Reports"},
  ];
  const [activeTab,setActiveTab]=useState("overview");
  const [saved,setSaved]=useState(false);
  const [testResult,setTestResult]=useState("");

  /* ── OTP state ── */
  const [otp,setOtp]=useState({
    smsProvider:"none", smsSenderId:"", smsApiKey:"", smsTemplateId:"",
    twilioSid:"", twilioFrom:"", emailOtpEnabled:false, emailProvider:"none", otpExpiryMinutes:10,
    testPhone:""
  });

  /* ── Email state ── */
  const [email,setEmail]=useState({
    provider:"none", sendgridKey:"", fromEmail:"", fromName:"MyTown 360",
    smtpHost:"", smtpPort:587, smtpUser:"", smtpPass:"", smtpSecure:false,
    welcomeEmail:true, verifyEmail:true, postApproved:true, eventReminder:true, reportAlert:true,
    testEmail:""
  });

  /* ── Notifications state ── */
  const [notif,setNotif]=useState({
    pushEnabled:false, fcmServerKey:"", fcmProjectId:"",
    smsAlertsEnabled:false, inAppEnabled:true,
    pushOnNewPost:true, pushOnReply:true, pushOnEvent:true, pushOnMessage:true, pushOnElection:true
  });

  /* ── Integrations state ── */
  const [integrations,setIntegrations]=useState([
    {key:"google_maps",  label:"Google Maps",       category:"maps",      icon:"🗺️",  enabled:false, apiKey:"", apiSecret:"", webhookUrl:""},
    {key:"razorpay",     label:"Razorpay",           category:"payments",  icon:"💳",  enabled:false, apiKey:"", apiSecret:"", webhookUrl:""},
    {key:"cloudinary",   label:"Cloudinary",         category:"media",     icon:"☁️",  enabled:false, apiKey:"", apiSecret:"", webhookUrl:""},
    {key:"aws_s3",       label:"AWS S3",             category:"media",     icon:"🪣",  enabled:false, apiKey:"", apiSecret:"", webhookUrl:""},
    {key:"firebase_fcm", label:"Firebase FCM",       category:"push",      icon:"🔔",  enabled:false, apiKey:"", apiSecret:"", webhookUrl:""},
    {key:"google_oauth", label:"Google OAuth",       category:"auth",      icon:"🔐",  enabled:false, apiKey:"", apiSecret:"", webhookUrl:""},
    {key:"sentry",       label:"Sentry (Errors)",    category:"analytics", icon:"🐛",  enabled:false, apiKey:"", apiSecret:"", webhookUrl:""},
    {key:"mixpanel",     label:"Mixpanel",           category:"analytics", icon:"📊",  enabled:false, apiKey:"", apiSecret:"", webhookUrl:""},
    {key:"msg91",        label:"MSG91 (SMS OTP)",    category:"sms",       icon:"📱",  enabled:false, apiKey:"", apiSecret:"", webhookUrl:""},
    {key:"twilio",       label:"Twilio (SMS/Voice)", category:"sms",       icon:"📞",  enabled:false, apiKey:"", apiSecret:"", webhookUrl:""},
    {key:"sendgrid",     label:"SendGrid",           category:"email",     icon:"✉️",  enabled:false, apiKey:"", apiSecret:"", webhookUrl:""},
    {key:"whatsapp_biz", label:"WhatsApp Business",  category:"messaging", icon:"💬",  enabled:false, apiKey:"", apiSecret:"", webhookUrl:""},
  ]);
  const [expandedIntg,setExpandedIntg]=useState(null);

  /* ── Mock users / reports ── */
  const [users]=useState([
    {id:"u2",name:"Ravi Kumar",    area:"EC Phase 1",apt:"Brigade Gateway",verified:false,isBanned:false,role:"resident",phone:"98765 43210",joined:"Jan 2025"},
    {id:"u3",name:"Priya Sharma",  area:"EC Phase 2",apt:"Prestige Tech Cloud",verified:true, isBanned:false,role:"resident",phone:"87654 32109",joined:"Feb 2025"},
    {id:"u4",name:"Arjun Nair",    area:"Electronic City",apt:"Sobha Dream Acres",verified:false,isBanned:true, role:"resident",phone:"76543 21098",joined:"Mar 2025"},
    {id:"u5",name:"Divya Menon",   area:"Hosa Road",apt:"Prestige Sunrise",verified:true, isBanned:false,role:"moderator",phone:"65432 10987",joined:"Dec 2024"},
    {id:"u6",name:"Mohammed Asif", area:"EC Phase 1",apt:"Mantri Lithos",verified:false,isBanned:false,role:"resident",phone:"54321 09876",joined:"Apr 2025"},
  ]);
  const [userSearch,setUserSearch]=useState("");
  const [userStates,setUserStates]=useState({});

  const filteredUsers=users.filter(u=>u.name.toLowerCase().includes(userSearch.toLowerCase())||u.area.toLowerCase().includes(userSearch.toLowerCase()));

  const [reports]=useState([
    {id:"r1",type:"post",  content:"Fake missing person post",    reporter:"Priya Sharma", date:"Today, 9:10 AM",  status:"pending", severity:"high"},
    {id:"r2",type:"user",  content:"Spamming multiple categories",reporter:"Ravi Kumar",   date:"Yesterday",       status:"pending", severity:"medium"},
    {id:"r3",type:"post",  content:"Inappropriate content in feed",reporter:"Divya Menon", date:"2 days ago",      status:"actioned",severity:"high"},
    {id:"r4",type:"listing",content:"Fake listing / scam",         reporter:"Arjun Nair",  date:"3 days ago",      status:"pending", severity:"medium"},
    {id:"r5",type:"post",  content:"Misinformation about COVID",   reporter:"Mohammed Asif",date:"1 week ago",     status:"dismissed",severity:"low"},
  ]);
  const [reportStates,setReportStates]=useState({});

  const showSaved=()=>{setSaved(true);setTimeout(()=>setSaved(false),2000);};

  /* ─── Styles ─── */
  const card={background:"#fff",borderRadius:14,padding:16,marginBottom:12,boxShadow:"0 1px 4px rgba(0,0,0,0.08)"};
  const label={display:"block",fontSize:12,fontWeight:700,color:"#555",marginBottom:4,marginTop:10};
  const input={width:"100%",padding:"9px 12px",borderRadius:8,border:"1.5px solid #E5E7EB",fontSize:14,outline:"none",boxSizing:"border-box",color:"#111"};
  const select={...input,background:"#fff"};
  const toggle=(val,onChg)=>(
    <div onClick={onChg} style={{width:44,height:24,borderRadius:12,background:val?"#7C3AED":"#CBD5E1",position:"relative",cursor:"pointer",transition:"background 0.2s",flexShrink:0}}>
      <div style={{position:"absolute",top:2,left:val?22:2,width:20,height:20,borderRadius:"50%",background:"#fff",boxShadow:"0 1px 3px rgba(0,0,0,0.2)",transition:"left 0.2s"}}/>
    </div>
  );
  const btn=(label,onClick,variant="primary")=>(
    <button onClick={onClick} style={{padding:"9px 18px",borderRadius:8,border:"none",cursor:"pointer",fontWeight:700,fontSize:13,
      background:variant==="primary"?C.purple:variant==="danger"?"#EF4444":variant==="success"?"#10B981":"#F3F4F6",
      color:variant==="ghost"?"#555":"#fff",marginRight:6,marginTop:8}}>
      {label}
    </button>
  );

  /* ─── OVERVIEW TAB ─── */
  const statsData=[
    {label:"Total Users",     value:"2,847", icon:"👥", color:"#7C3AED",bg:"#EDE9FE"},
    {label:"Verified",        value:"1,203", icon:"✅", color:"#10B981",bg:"#D1FAE5"},
    {label:"Posts Today",     value:"48",    icon:"📝", color:"#0EA5E9",bg:"#E0F2FE"},
    {label:"Pending Reports", value:"4",     icon:"🚩", color:"#EF4444",bg:"#FEE2E2"},
    {label:"Active Businesses",value:"34",  icon:"🏪", color:"#F59E0B",bg:"#FEF3C7"},
    {label:"Events This Week",value:"12",   icon:"📅", color:"#8B5CF6",bg:"#EDE9FE"},
  ];

  /* ─── RENDER ─── */
  return(
    <div style={{background:"#F0F2F5",minHeight:"100vh",paddingBottom:80}}>
      {/* Header */}
      <div style={{background:"#fff",padding:"12px 16px",display:"flex",alignItems:"center",gap:10,borderBottom:"1px solid #E5E7EB",position:"sticky",top:0,zIndex:20}}>
        <button onClick={()=>nav("feed")} style={{background:"none",border:"none",fontSize:20,cursor:"pointer",padding:"0 4px"}}>←</button>
        <div>
          <div style={{fontWeight:900,fontSize:16,color:C.purple}}>⚙️ Admin Panel</div>
          <div style={{fontSize:11,color:"#888"}}>MyTown 360 · Super Admin</div>
        </div>
        {saved&&<div style={{marginLeft:"auto",background:"#D1FAE5",color:"#065F46",padding:"4px 10px",borderRadius:20,fontSize:12,fontWeight:700}}>✅ Saved</div>}
      </div>

      {/* Tab bar */}
      <div style={{display:"flex",overflowX:"auto",background:"#fff",borderBottom:"1px solid #E5E7EB",padding:"0 4px"}}>
        {TABS.map(t=>(
          <button key={t.id} onClick={()=>setActiveTab(t.id)} style={{
            flexShrink:0,padding:"10px 12px",border:"none",background:"none",cursor:"pointer",
            fontSize:12,fontWeight:700,
            color:activeTab===t.id?C.purple:"#888",
            borderBottom:activeTab===t.id?`2px solid ${C.purple}`:"2px solid transparent",
            whiteSpace:"nowrap"
          }}>
            {t.icon} {t.label}
          </button>
        ))}
      </div>

      <div style={{padding:"12px 12px 0"}}>

        {/* ── OVERVIEW ── */}
        {activeTab==="overview"&&(
          <>
            <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10,marginBottom:12}}>
              {statsData.map(s=>(
                <div key={s.label} style={{...card,padding:14,marginBottom:0,display:"flex",alignItems:"center",gap:10}}>
                  <div style={{width:40,height:40,borderRadius:10,background:s.bg,display:"flex",alignItems:"center",justifyContent:"center",fontSize:18}}>{s.icon}</div>
                  <div>
                    <div style={{fontSize:20,fontWeight:900,color:s.color}}>{s.value}</div>
                    <div style={{fontSize:11,color:"#888",fontWeight:600}}>{s.label}</div>
                  </div>
                </div>
              ))}
            </div>
            <div style={card}>
              <div style={{fontWeight:800,fontSize:14,color:"#111",marginBottom:10}}>⚡ Quick Actions</div>
              {[
                {icon:"🔑",label:"Configure OTP Provider",  sub:"SMS & Email OTP",  tab:"otp"},
                {icon:"✉️",label:"Setup Email Service",     sub:"SendGrid / SMTP",  tab:"email"},
                {icon:"🔔",label:"Push Notifications",      sub:"Firebase FCM",     tab:"notif"},
                {icon:"🔌",label:"Third-party Integrations",sub:"APIs & SDKs",      tab:"integrations"},
                {icon:"👥",label:"Manage Users",            sub:"Verify, ban, roles",tab:"users"},
                {icon:"🚩",label:"Review Reports",          sub:"4 pending",        tab:"reports"},
              ].map(q=>(
                <div key={q.tab} onClick={()=>setActiveTab(q.tab)} style={{display:"flex",alignItems:"center",gap:10,padding:"10px 0",borderBottom:"1px solid #F3F4F6",cursor:"pointer"}}>
                  <div style={{width:36,height:36,borderRadius:9,background:C.purpleL,display:"flex",alignItems:"center",justifyContent:"center",fontSize:16}}>{q.icon}</div>
                  <div style={{flex:1}}>
                    <div style={{fontWeight:700,fontSize:13,color:"#111"}}>{q.label}</div>
                    <div style={{fontSize:11,color:"#888"}}>{q.sub}</div>
                  </div>
                  <span style={{color:"#bbb",fontSize:16}}>›</span>
                </div>
              ))}
            </div>
          </>
        )}

        {/* ── OTP TAB ── */}
        {activeTab==="otp"&&(
          <>
            <div style={card}>
              <div style={{fontWeight:800,fontSize:14,color:"#111",marginBottom:4}}>📱 SMS OTP Provider</div>
              <div style={{fontSize:12,color:"#888",marginBottom:10}}>Used for phone verification during signup & login.</div>

              <span style={label}>Provider</span>
              <select style={select} value={otp.smsProvider} onChange={e=>setOtp({...otp,smsProvider:e.target.value})}>
                <option value="none">— Not configured —</option>
                <option value="msg91">MSG91</option>
                <option value="twilio">Twilio</option>
                <option value="2factor">2Factor.in</option>
              </select>

              {otp.smsProvider==="msg91"&&(<>
                <span style={label}>MSG91 Auth Key</span>
                <input style={input} type="password" placeholder="Enter MSG91 API key" value={otp.smsApiKey} onChange={e=>setOtp({...otp,smsApiKey:e.target.value})}/>
                <span style={label}>Sender ID</span>
                <input style={input} placeholder="e.g. MTWN36" value={otp.smsSenderId} onChange={e=>setOtp({...otp,smsSenderId:e.target.value})}/>
                <span style={label}>Flow / Template ID</span>
                <input style={input} placeholder="MSG91 flow ID" value={otp.smsTemplateId} onChange={e=>setOtp({...otp,smsTemplateId:e.target.value})}/>
              </>)}

              {otp.smsProvider==="twilio"&&(<>
                <span style={label}>Account SID</span>
                <input style={input} type="password" placeholder="ACxxxxxxxxxx" value={otp.twilioSid} onChange={e=>setOtp({...otp,twilioSid:e.target.value})}/>
                <span style={label}>Auth Token</span>
                <input style={input} type="password" placeholder="Twilio auth token" value={otp.smsApiKey} onChange={e=>setOtp({...otp,smsApiKey:e.target.value})}/>
                <span style={label}>From Number</span>
                <input style={input} placeholder="+1 234 567 8900" value={otp.twilioFrom} onChange={e=>setOtp({...otp,twilioFrom:e.target.value})}/>
              </>)}

              {otp.smsProvider==="2factor"&&(<>
                <span style={label}>2Factor API Key</span>
                <input style={input} type="password" placeholder="2Factor API key" value={otp.smsApiKey} onChange={e=>setOtp({...otp,smsApiKey:e.target.value})}/>
                <span style={label}>Template Name</span>
                <input style={input} placeholder="OTPTEMPLATE" value={otp.smsTemplateId} onChange={e=>setOtp({...otp,smsTemplateId:e.target.value})}/>
              </>)}

              <span style={label}>OTP Expiry (minutes)</span>
              <input style={input} type="number" min={5} max={60} value={otp.otpExpiryMinutes} onChange={e=>setOtp({...otp,otpExpiryMinutes:+e.target.value})}/>
            </div>

            <div style={card}>
              <div style={{fontWeight:800,fontSize:14,color:"#111",marginBottom:4}}>📧 Email OTP</div>
              <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:10}}>
                <span style={{fontSize:13,color:"#555"}}>Enable email OTP as fallback</span>
                {toggle(otp.emailOtpEnabled,()=>setOtp({...otp,emailOtpEnabled:!otp.emailOtpEnabled}))}
              </div>
              {otp.emailOtpEnabled&&(
                <>
                  <span style={label}>Email Provider for OTP</span>
                  <select style={select} value={otp.emailProvider} onChange={e=>setOtp({...otp,emailProvider:e.target.value})}>
                    <option value="none">— Select provider —</option>
                    <option value="sendgrid">SendGrid</option>
                    <option value="smtp">Custom SMTP</option>
                  </select>
                  <div style={{fontSize:12,color:"#888",marginTop:6}}>Configure provider details in the Email tab.</div>
                </>
              )}
            </div>

            <div style={card}>
              <div style={{fontWeight:800,fontSize:14,color:"#111",marginBottom:8}}>🧪 Test OTP</div>
              <input style={input} placeholder="+91 98765 43210" value={otp.testPhone} onChange={e=>setOtp({...otp,testPhone:e.target.value})}/>
              {btn("Send Test OTP",()=>{setTestResult("✅ Test OTP sent! Check the phone.");setTimeout(()=>setTestResult(""),4000);},"primary")}
              {testResult&&<div style={{marginTop:8,fontSize:13,color:"#065F46",background:"#D1FAE5",padding:"8px 12px",borderRadius:8}}>{testResult}</div>}
            </div>

            {btn("Save OTP Settings",showSaved)}
          </>
        )}

        {/* ── EMAIL TAB ── */}
        {activeTab==="email"&&(
          <>
            <div style={card}>
              <div style={{fontWeight:800,fontSize:14,color:"#111",marginBottom:4}}>📨 Email Provider</div>
              <span style={label}>Provider</span>
              <select style={select} value={email.provider} onChange={e=>setEmail({...email,provider:e.target.value})}>
                <option value="none">— Not configured —</option>
                <option value="sendgrid">SendGrid</option>
                <option value="smtp">Custom SMTP</option>
              </select>

              {email.provider==="sendgrid"&&(<>
                <span style={label}>SendGrid API Key</span>
                <input style={input} type="password" placeholder="SG.xxxxxxxxxxxxxxxx" value={email.sendgridKey} onChange={e=>setEmail({...email,sendgridKey:e.target.value})}/>
              </>)}

              {email.provider==="smtp"&&(<>
                <span style={label}>SMTP Host</span>
                <input style={input} placeholder="smtp.example.com" value={email.smtpHost} onChange={e=>setEmail({...email,smtpHost:e.target.value})}/>
                <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8}}>
                  <div>
                    <span style={label}>Port</span>
                    <input style={input} type="number" value={email.smtpPort} onChange={e=>setEmail({...email,smtpPort:+e.target.value})}/>
                  </div>
                  <div>
                    <span style={{...label,marginTop:10}}>TLS</span>
                    <div style={{paddingTop:8,display:"flex",alignItems:"center",gap:8}}>
                      {toggle(email.smtpSecure,()=>setEmail({...email,smtpSecure:!email.smtpSecure}))}
                      <span style={{fontSize:12,color:"#555"}}>{email.smtpSecure?"On":"Off"}</span>
                    </div>
                  </div>
                </div>
                <span style={label}>Username</span>
                <input style={input} placeholder="smtp@example.com" value={email.smtpUser} onChange={e=>setEmail({...email,smtpUser:e.target.value})}/>
                <span style={label}>Password</span>
                <input style={input} type="password" placeholder="SMTP password" value={email.smtpPass} onChange={e=>setEmail({...email,smtpPass:e.target.value})}/>
              </>)}

              {email.provider!=="none"&&(<>
                <span style={label}>From Email</span>
                <input style={input} placeholder="noreply@mytown360.in" value={email.fromEmail} onChange={e=>setEmail({...email,fromEmail:e.target.value})}/>
                <span style={label}>From Name</span>
                <input style={input} placeholder="MyTown 360" value={email.fromName} onChange={e=>setEmail({...email,fromName:e.target.value})}/>
              </>)}
            </div>

            <div style={card}>
              <div style={{fontWeight:800,fontSize:14,color:"#111",marginBottom:10}}>📬 Email Triggers</div>
              {[
                {key:"welcomeEmail",  label:"Welcome email on signup"},
                {key:"verifyEmail",   label:"Account verification"},
                {key:"postApproved",  label:"Post approved notification"},
                {key:"eventReminder", label:"Event reminders (24 hrs before)"},
                {key:"reportAlert",   label:"Report alerts to admin"},
              ].map(t=>(
                <div key={t.key} style={{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 0",borderBottom:"1px solid #F3F4F6"}}>
                  <span style={{fontSize:13,color:"#333"}}>{t.label}</span>
                  {toggle(email[t.key],()=>setEmail({...email,[t.key]:!email[t.key]}))}
                </div>
              ))}
            </div>

            <div style={card}>
              <div style={{fontWeight:800,fontSize:14,color:"#111",marginBottom:8}}>🧪 Send Test Email</div>
              <input style={input} placeholder="test@example.com" value={email.testEmail} onChange={e=>setEmail({...email,testEmail:e.target.value})}/>
              {btn("Send Test Email",()=>{setTestResult("✅ Test email queued!");setTimeout(()=>setTestResult(""),4000);},"primary")}
              {testResult&&<div style={{marginTop:8,fontSize:13,color:"#065F46",background:"#D1FAE5",padding:"8px 12px",borderRadius:8}}>{testResult}</div>}
            </div>

            {btn("Save Email Settings",showSaved)}
          </>
        )}

        {/* ── NOTIFICATIONS TAB ── */}
        {activeTab==="notif"&&(
          <>
            <div style={card}>
              <div style={{fontWeight:800,fontSize:14,color:"#111",marginBottom:10}}>🔔 Push Notifications (FCM)</div>
              <div style={{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:10}}>
                <span style={{fontSize:13,color:"#555"}}>Enable Push Notifications</span>
                {toggle(notif.pushEnabled,()=>setNotif({...notif,pushEnabled:!notif.pushEnabled}))}
              </div>
              {notif.pushEnabled&&(<>
                <span style={label}>Firebase Project ID</span>
                <input style={input} placeholder="mytown360-xxxxx" value={notif.fcmProjectId} onChange={e=>setNotif({...notif,fcmProjectId:e.target.value})}/>
                <span style={label}>FCM Server Key (Legacy) / Service Account JSON Path</span>
                <input style={input} type="password" placeholder="AAAA:xxxxxxxxxxx" value={notif.fcmServerKey} onChange={e=>setNotif({...notif,fcmServerKey:e.target.value})}/>
                <div style={{fontSize:11,color:"#888",marginTop:4}}>Find this in Firebase Console → Project Settings → Cloud Messaging</div>
              </>)}
            </div>

            <div style={card}>
              <div style={{fontWeight:800,fontSize:14,color:"#111",marginBottom:10}}>📱 SMS Alerts</div>
              <div style={{display:"flex",alignItems:"center",justifyContent:"space-between"}}>
                <div>
                  <div style={{fontSize:13,color:"#333"}}>Enable SMS alerts</div>
                  <div style={{fontSize:11,color:"#888"}}>Uses your SMS OTP provider</div>
                </div>
                {toggle(notif.smsAlertsEnabled,()=>setNotif({...notif,smsAlertsEnabled:!notif.smsAlertsEnabled}))}
              </div>
            </div>

            <div style={card}>
              <div style={{fontWeight:800,fontSize:14,color:"#111",marginBottom:10}}>🔔 Push Triggers</div>
              {[
                {key:"pushOnNewPost", label:"New community post"},
                {key:"pushOnReply",   label:"Replies to user posts"},
                {key:"pushOnEvent",   label:"New events in area"},
                {key:"pushOnMessage", label:"New direct messages"},
                {key:"pushOnElection",label:"Election / voting updates"},
              ].map(t=>(
                <div key={t.key} style={{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"8px 0",borderBottom:"1px solid #F3F4F6"}}>
                  <span style={{fontSize:13,color:"#333"}}>{t.label}</span>
                  {toggle(notif[t.key],()=>setNotif({...notif,[t.key]:!notif[t.key]}))}
                </div>
              ))}
            </div>

            <div style={card}>
              <div style={{fontWeight:800,fontSize:14,color:"#111",marginBottom:4}}>🔔 In-App Notifications</div>
              <div style={{display:"flex",alignItems:"center",justifyContent:"space-between"}}>
                <span style={{fontSize:13,color:"#555"}}>Show in-app notification bell</span>
                {toggle(notif.inAppEnabled,()=>setNotif({...notif,inAppEnabled:!notif.inAppEnabled}))}
              </div>
            </div>

            {btn("Save Notification Settings",showSaved)}
          </>
        )}

        {/* ── INTEGRATIONS TAB ── */}
        {activeTab==="integrations"&&(
          <>
            <div style={{fontSize:12,color:"#888",marginBottom:8,padding:"0 2px"}}>Tap any integration to expand and configure its API keys.</div>
            {["auth","payments","media","push","sms","email","maps","analytics","messaging"].map(cat=>{
              const catItems=integrations.filter(i=>i.category===cat);
              if(!catItems.length) return null;
              const catLabels={auth:"🔐 Auth",payments:"💳 Payments",media:"📸 Media & Storage",push:"🔔 Push",sms:"📱 SMS",email:"✉️ Email",maps:"🗺️ Maps",analytics:"📊 Analytics",messaging:"💬 Messaging"};
              return(
                <div key={cat} style={{marginBottom:12}}>
                  <div style={{fontSize:11,fontWeight:800,color:C.purple,marginBottom:6,textTransform:"uppercase",letterSpacing:1}}>{catLabels[cat]||cat}</div>
                  {catItems.map(intg=>(
                    <div key={intg.key} style={{background:"#fff",borderRadius:12,marginBottom:8,overflow:"hidden",boxShadow:"0 1px 3px rgba(0,0,0,0.08)"}}>
                      {/* Header row */}
                      <div style={{display:"flex",alignItems:"center",gap:10,padding:"12px 14px",cursor:"pointer"}}
                           onClick={()=>setExpandedIntg(expandedIntg===intg.key?null:intg.key)}>
                        <div style={{width:36,height:36,borderRadius:9,background:intg.enabled?"#EDE9FE":"#F3F4F6",display:"flex",alignItems:"center",justifyContent:"center",fontSize:18}}>{intg.icon}</div>
                        <div style={{flex:1}}>
                          <div style={{fontWeight:700,fontSize:13,color:"#111"}}>{intg.label}</div>
                          <div style={{fontSize:11,color:intg.enabled?"#7C3AED":"#9CA3AF",fontWeight:600}}>{intg.enabled?"● Active":"○ Inactive"}</div>
                        </div>
                        {toggle(intg.enabled,()=>setIntegrations(integrations.map(i=>i.key===intg.key?{...i,enabled:!i.enabled}:i)))}
                        <span style={{color:"#bbb",fontSize:14,marginLeft:4}}>{expandedIntg===intg.key?"▲":"▼"}</span>
                      </div>
                      {/* Expanded config */}
                      {expandedIntg===intg.key&&(
                        <div style={{padding:"0 14px 14px",borderTop:"1px solid #F3F4F6"}}>
                          <span style={label}>API Key / Client ID</span>
                          <input style={input} type="password" placeholder="Enter API key" value={intg.apiKey}
                            onChange={e=>setIntegrations(integrations.map(i=>i.key===intg.key?{...i,apiKey:e.target.value}:i))}/>
                          <span style={label}>API Secret / Client Secret</span>
                          <input style={input} type="password" placeholder="Enter secret" value={intg.apiSecret}
                            onChange={e=>setIntegrations(integrations.map(i=>i.key===intg.key?{...i,apiSecret:e.target.value}:i))}/>
                          <span style={label}>Webhook URL (optional)</span>
                          <input style={input} placeholder="https://mytown360.in/api/v1/webhooks/..." value={intg.webhookUrl}
                            onChange={e=>setIntegrations(integrations.map(i=>i.key===intg.key?{...i,webhookUrl:e.target.value}:i))}/>
                          {btn("Save",showSaved,"primary")}
                          {btn("Remove",()=>setIntegrations(integrations.map(i=>i.key===intg.key?{...i,apiKey:"",apiSecret:"",webhookUrl:"",enabled:false}:i)),"danger")}
                        </div>
                      )}
                    </div>
                  ))}
                </div>
              );
            })}
          </>
        )}

        {/* ── USERS TAB ── */}
        {activeTab==="users"&&(
          <>
            <div style={{...card,padding:"10px 12px"}}>
              <input style={{...input,marginBottom:0}} placeholder="🔍  Search by name or area..." value={userSearch} onChange={e=>setUserSearch(e.target.value)}/>
            </div>
            {filteredUsers.map(u=>{
              const st=userStates[u.id]||{verified:u.verified,isBanned:u.isBanned};
              return(
                <div key={u.id} style={card}>
                  <div style={{display:"flex",alignItems:"center",gap:10,marginBottom:8}}>
                    <div style={{width:40,height:40,borderRadius:"50%",background:C.purpleL,display:"flex",alignItems:"center",justifyContent:"center",fontWeight:900,color:C.purple,fontSize:14}}>
                      {u.name.split(" ").map(n=>n[0]).join("")}
                    </div>
                    <div style={{flex:1}}>
                      <div style={{fontWeight:800,fontSize:13,color:"#111"}}>{u.name}</div>
                      <div style={{fontSize:11,color:"#888"}}>{u.apt} · {u.area}</div>
                      <div style={{fontSize:11,color:"#888"}}>📱 {u.phone} · Joined {u.joined}</div>
                    </div>
                    <span style={{fontSize:11,fontWeight:700,padding:"3px 8px",borderRadius:20,background:u.role==="admin"?"#EDE9FE":u.role==="moderator"?"#D1FAE5":"#F3F4F6",color:u.role==="admin"?C.purple:u.role==="moderator"?"#065F46":"#555"}}>
                      {u.role}
                    </span>
                  </div>
                  <div style={{display:"flex",gap:6,flexWrap:"wrap"}}>
                    {!st.verified&&btn("✅ Verify",()=>setUserStates({...userStates,[u.id]:{...st,verified:true}}),"success")}
                    {st.verified&&<span style={{fontSize:12,fontWeight:700,color:"#10B981",padding:"6px 12px"}}>✅ Verified</span>}
                    {!st.isBanned&&btn("🚫 Ban",()=>setUserStates({...userStates,[u.id]:{...st,isBanned:true}}),"danger")}
                    {st.isBanned&&btn("↩️ Unban",()=>setUserStates({...userStates,[u.id]:{...st,isBanned:false}}),"ghost")}
                  </div>
                  {st.isBanned&&<div style={{fontSize:12,color:"#EF4444",fontWeight:700,marginTop:6}}>⛔ This user is banned</div>}
                </div>
              );
            })}
          </>
        )}

        {/* ── REPORTS TAB ── */}
        {activeTab==="reports"&&(
          <>
            {reports.map(r=>{
              const st=reportStates[r.id]||r.status;
              const sevColor={high:"#EF4444",medium:"#F59E0B",low:"#6B7280"}[r.severity]||"#888";
              const typeIcon={post:"📝",user:"👤",listing:"🏪"}[r.type]||"🚩";
              return(
                <div key={r.id} style={{...card,borderLeft:`4px solid ${sevColor}`}}>
                  <div style={{display:"flex",alignItems:"center",gap:8,marginBottom:6}}>
                    <span style={{fontSize:18}}>{typeIcon}</span>
                    <div style={{flex:1}}>
                      <div style={{fontWeight:800,fontSize:13,color:"#111"}}>{r.content}</div>
                      <div style={{fontSize:11,color:"#888"}}>Reported by {r.reporter} · {r.date}</div>
                    </div>
                    <span style={{fontSize:10,fontWeight:800,padding:"3px 8px",borderRadius:20,
                      background:st==="pending"?"#FEE2E2":st==="actioned"?"#D1FAE5":"#F3F4F6",
                      color:st==="pending"?"#EF4444":st==="actioned"?"#065F46":"#6B7280",textTransform:"uppercase"}}>
                      {st}
                    </span>
                  </div>
                  {st==="pending"&&(
                    <div style={{display:"flex",gap:6}}>
                      {btn("✅ Action",()=>setReportStates({...reportStates,[r.id]:"actioned"}),"danger")}
                      {btn("❌ Dismiss",()=>setReportStates({...reportStates,[r.id]:"dismissed"}),"ghost")}
                    </div>
                  )}
                </div>
              );
            })}
          </>
        )}

      </div>
    </div>
  );
}

// ─── Root App ──────────────────────────────────────────────────────────────────
export default function MyTown360(){
  const [screen,setScreen]=useState("landing");
  const [tab,setTab]=useState("feed");
  const [sidebarOpen,setSidebarOpen]=useState(false);
  const nav=(s)=>{
    const appTabs=["feed","events","map","messages","profile","community"];
    if(s==="community_apply"){setScreen("app");setTab("community");}
    else if(s==="contact_admin"){setScreen("admin_directory");}
    else if(s==="admin_panel"){window.open("/admin","_blank");}
    else if(appTabs.includes(s)){setScreen("app");setTab(s);}
    else setScreen(s);
  };
  if(screen==="landing")         return <><GlobalStyles/><LandingScreen nav={nav}/></>;
  if(screen==="login")           return <><GlobalStyles/><LoginScreen nav={nav}/></>;
  if(screen==="forgot")          return <><GlobalStyles/><ForgotScreen nav={nav}/></>;
  if(screen==="signup")          return <><GlobalStyles/><SignupScreen nav={nav}/></>;
  if(screen==="helplines") return(
    <div className="min-h-screen" style={{background:C.surface}}>
      <Sidebar open={sidebarOpen} onClose={()=>setSidebarOpen(false)} nav={nav} activeTab=""/>
      <HelplineScreen nav={nav}/>
      <BottomNav tab="" setTab={(t)=>{setScreen("app");setTab(t);}}/>
    </div>
  );
  if(screen==="admin_directory") return(
    <div className="min-h-screen" style={{background:C.surface}}>
      <Sidebar open={sidebarOpen} onClose={()=>setSidebarOpen(false)} nav={nav} activeTab=""/>
      <TopBar setScreen={nav} onMenuOpen={()=>setSidebarOpen(true)}/>
      <div className="pb-20"><AdminDirectoryScreen nav={nav}/></div>
      <BottomNav tab="" setTab={(t)=>{setScreen("app");setTab(t);}}/>
    </div>
  );
  if(screen==="admin_panel") return(
    <div style={{maxWidth:480,margin:"0 auto",minHeight:"100dvh"}}>
      <AdminPanelScreen nav={nav}/>
    </div>
  );
  return(
    <div style={{minHeight:"100dvh",background:C.surface,maxWidth:480,margin:"0 auto",position:"relative",overflowX:"hidden"}}>
      <GlobalStyles/>
      <Sidebar open={sidebarOpen} onClose={()=>setSidebarOpen(false)} nav={nav} activeTab={tab}/>
      <TopBar setScreen={nav} onMenuOpen={()=>setSidebarOpen(true)}/>
      <div style={{paddingBottom:80,paddingTop:60}}>
        {tab==="feed"      &&<FeedScreen/>}
        {tab==="events"    &&<EventsScreen/>}
        {tab==="community" &&<CommunityManagerScreen/>}
        {tab==="map"       &&<MapScreen/>}
        {tab==="messages"  &&<MessagesScreen/>}
        {tab==="profile"   &&<ProfileScreen nav={nav}/>}
      </div>
      <BottomNav tab={tab} setTab={setTab}/>
    </div>
  );
}

// ── Browser render entry point (CDN / Babel standalone deployment) ──────────
if (typeof window !== "undefined" && typeof ReactDOM !== "undefined") {
  window.MyTown360 = MyTown360;
}
