// BetyChef — All views
const { useState: useS, useMemo, useRef: useR } = React;

const egp  = v => "EGP " + Math.round(v).toLocaleString();
const egpK = v => v >= 1000 ? "EGP " + (v/1000).toFixed(v>=10000?0:1)+"K" : "EGP "+v;
const pct  = (a, b) => b > 0 ? Math.round(a/b*100) : 0;
// milliseconds from a Firestore timestamp / date (0 if missing) — for newest-first sorts
const tsMs = ts => ts ? (ts.toDate ? ts.toDate().getTime() : new Date(ts).getTime()) : 0;

/* ══════════════════════════════ OVERVIEW ════════════════════════════════ */
function OverviewView({ navigate }) {
  const { can } = usePermissions();
  const { kpis, northStar: ns, ordersByDay, areas, activity, ops, prospects } = window.BC;
  const accentColor = { primary:"var(--c-primary)", green:"var(--c-green)", saffron:"var(--c-saffron)", ink:"var(--c-ink-spark)" };
  const fmt = k => k.unit==="EGP" ? egpK(k.value) : k.value.toLocaleString()+(k.suffix||"");
  const MONEY_KPIS = ["gmv","revenue"];   // commission/revenue figures — gated by sensitive.viewFinancials

  // Outreach stats
  const prospectStats = useMemo(() => {
    const prosList = prospects || [];
    const contacted = prosList.filter(p => p.status === "Contacted").length;
    const interested = prosList.filter(p => p.status === "Interested").length;
    const converted = prosList.filter(p => p.status === "Converted").length;
    return { total: prosList.length, contacted, interested, converted, conversionRate: prosList.length ? Math.round(converted/prosList.length*100) : 0 };
  }, [prospects]);

  return (
    <div className="bc-stack">
      {/* KPI row */}
      <div className="bc-kpi-grid">
        {(kpis||[]).map(k => (
          <div key={k.id} className={"bc-card bc-kpi-card bc-kpi--"+k.accent}
            onClick={() => navigate(k.nav, k.navFilter)} title="Click to view details"
            style={{cursor:"pointer"}}>
            <div className="bc-kpi-top">
              <span className="bc-kpi-label">{k.label}</span>
            </div>
            <div className="bc-kpi-value">
              {MONEY_KPIS.includes(k.id) && !can("sensitive","viewFinancials")
                ? <span className="bc-redacted" title="Hidden by your permissions"><Icon name="key" size={13}/>•••</span>
                : fmt(k)}
            </div>
            <Sparkline data={k.spark} color={accentColor[k.accent]||"var(--c-ink-spark)"}/>
            <div className="bc-kpi-nav-hint">→ View details</div>
          </div>
        ))}
      </div>

      <div className="bc-grid bc-grid--overview">
        {/* Orders chart */}
        <div className="bc-card bc-span-8">
          <div className="bc-card-head">
            <div>
              <h2 className="bc-card-title">Orders this week</h2>
              <p className="bc-card-sub">{(ordersByDay||[]).reduce((s,d)=>s+d.repeat+d.first,0)} total</p>
            </div>
            <div className="bc-chip-legend">
              <span><i style={{background:"var(--c-primary)"}}/>Repeat</span>
              <span><i style={{background:"var(--c-saffron)"}}/>First-time</span>
            </div>
          </div>
          <StackedBars data={ordersByDay||[]}/>
        </div>

        {/* Pipeline */}
        <div className="bc-card bc-span-4">
          <div className="bc-card-head"><h2 className="bc-card-title">Chef pipeline</h2></div>
          <Pipeline stages={[
            { label:"Pending", n:ns.pending||0, color:"var(--c-saffron)" },
            { label:"Active",  n:ns.active||0,  color:"var(--c-green)"   },
            { label:"Paused",  n:ns.paused||0,  color:"var(--c-line-2)"  },
            { label:"Rejected",n:ns.rejected||0,color:"#C2410C"          },
          ]}/>
          {(ns.pending||0) > 0 && (
            <div className="bc-pipe-note">
              <Icon name="alert" size={14}/> {ns.pending} application{ns.pending!==1?"s":""} waiting for review
            </div>
          )}
        </div>
      </div>

      <div className="bc-grid bc-grid--overview">
        {/* Areas */}
        <div className="bc-card bc-span-4">
          <div className="bc-card-head"><h2 className="bc-card-title">Chefs by area</h2></div>
          <AreaBars areas={(areas||[]).slice(0,6)}/>
        </div>

        {/* Ops */}
        <div className="bc-card bc-span-4 bc-ops-glance">
          <div className="bc-card-head"><h2 className="bc-card-title">Ops health</h2></div>
          <div className="bc-ops-row">
            <span className="bc-ops-ic bc-ops-ic--run"><Icon name="truck" size={16}/></span>
            <div><b>Runners Co.</b>
              <span>{ops.runners.deliveriesToday} deliveries · {ops.runners.successRate}% success</span>
            </div>
            <Pill status="Connected" sm/>
          </div>
          <div className="bc-ops-row">
            <span className="bc-ops-ic bc-ops-ic--pay"><Icon name="card" size={16}/></span>
            <div><b>Paymob</b>
              <span>{ops.paymob.txToday} payments · <Gate need="sensitive" action="viewFinancials">{egpK(ops.paymob.collectedToday)}</Gate></span>
            </div>
            <Pill status="Connected" sm/>
          </div>
          {can("sensitive","viewFinancials") ? (
            <div className="bc-budget">
              <div className="bc-budget-row"><span>Settled to chefs (MTD)</span><b>{egp(ops.paymob.settledMtd)}</b></div>
              <div className="bc-meter"><div style={{width:"78%"}}/></div>
              <div className="bc-budget-row bc-budget-row--sub"><span>Pending</span><span>{egp(ops.paymob.pending)}</span></div>
            </div>
          ) : (
            <div className="bc-budget-row" style={{padding:"10px 0"}}><span className="bc-redacted"><Icon name="key" size={11}/>Settlement figures hidden</span></div>
          )}
        </div>

        {/* Live activity */}
        <div className="bc-card bc-span-4">
          <div className="bc-card-head">
            <h2 className="bc-card-title">Live activity</h2>
            <span className="bc-livepill"><span className="bc-livedot"/>Live</span>
          </div>
          <ul className="bc-feed">
            {(activity||[]).map((a,i)=>(
              <li key={i} className="bc-feed-item">
                <span className={"bc-feed-ic bc-feed-ic--"+(a.type||"order")}>
                  <Icon name={({verify:"verify",order:"orders",delivery:"truck",milestone:"star",payment:"card",apply:"chefs",remove:"x"}[a.type])||"dot"} size={14} stroke={2}/>
                </span>
                <span className="bc-feed-text"><b>{a.who}</b> {a.what}</span>
                <span className="bc-feed-when">{a.when}</span>
              </li>
            ))}
            {(!activity||activity.length===0) && <li className="bc-empty" style={{padding:"20px 0"}}>No activity yet today</li>}
          </ul>
        </div>
      </div>

      {/* Outreach / CRM Section */}
      <div className="bc-grid bc-grid--overview">
        <div className="bc-card bc-span-12">
          <div className="bc-card-head">
            <h2 className="bc-card-title">📞 Outreach Pipeline</h2>
            <span style={{fontSize:12,color:"var(--c-ink-2)"}}>Chef acquisition prospects</span>
          </div>
          <div style={{display:"grid",gridTemplateColumns:"repeat(5,1fr)",gap:16}}>
            <div style={{padding:12,borderRadius:8,background:"var(--c-surface-2)"}}>
              <div style={{fontSize:12,color:"var(--c-ink-2)",marginBottom:4}}>Total prospects</div>
              <div style={{fontSize:24,fontWeight:700,color:"var(--c-ink)"}}>{prospectStats.total}</div>
            </div>
            <div style={{padding:12,borderRadius:8,background:"rgba(155,236,0,0.1)"}}>
              <div style={{fontSize:12,color:"var(--c-ink-2)",marginBottom:4}}>Contacted</div>
              <div style={{fontSize:24,fontWeight:700,color:"var(--c-saffron)"}}>{prospectStats.contacted}</div>
              <div style={{fontSize:11,color:"var(--c-ink-2)",marginTop:4}}>{prospectStats.total ? Math.round(prospectStats.contacted/prospectStats.total*100) : 0}% contacted</div>
            </div>
            <div style={{padding:12,borderRadius:8,background:"rgba(6,208,1,0.1)"}}>
              <div style={{fontSize:12,color:"var(--c-ink-2)",marginBottom:4}}>Interested</div>
              <div style={{fontSize:24,fontWeight:700,color:"var(--c-primary-text)"}}>{prospectStats.interested}</div>
              <div style={{fontSize:11,color:"var(--c-ink-2)",marginTop:4}}>{prospectStats.total ? Math.round(prospectStats.interested/prospectStats.total*100) : 0}% interested</div>
            </div>
            <div style={{padding:12,borderRadius:8,background:"rgba(6,208,1,0.15)"}}>
              <div style={{fontSize:12,color:"var(--c-ink-2)",marginBottom:4}}>Converted</div>
              <div style={{fontSize:24,fontWeight:700,color:"var(--c-green)"}}>{prospectStats.converted}</div>
              <div style={{fontSize:11,color:"var(--c-ink-2)",marginTop:4}}>✓ Signed up</div>
            </div>
            <div style={{padding:12,borderRadius:8,background:"rgba(10,158,22,0.15)"}}>
              <div style={{fontSize:12,color:"var(--c-ink-2)",marginBottom:4}}>Conversion rate</div>
              <div style={{fontSize:24,fontWeight:700,color:"var(--c-green)"}}>{prospectStats.conversionRate}%</div>
              <div style={{fontSize:11,color:"var(--c-ink-2)",marginTop:4}}>overall rate</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ══════════════════════════════ CHEFS ═══════════════════════════════════ */
function ChefsView({ query, navigate }) {
  const { can } = usePermissions();
  const { chefs, chefStatuses } = window.BC;
  const [status,    setStatus]  = useS("All");
  const [active,    setActive]  = useS(null);
  const [addOpen,   setAddOpen] = useS(false);
  const [page,      setPage]    = useS(0);

  // Open a chef's detail when arriving from global search
  React.useEffect(() => {
    function openPending() {
      const p = window.BC._pendingDetail;
      if (p && p.view === "chefs") {
        const item = (window.BC.chefs || []).find(c => c.docId === p.docId);
        if (item) setActive(item);
        window.BC._pendingDetail = null;
      }
    }
    openPending();
    window.addEventListener("bc-open-detail", openPending);
    return () => window.removeEventListener("bc-open-detail", openPending);
  }, []);
  const [areaFilter, setAreaFilter] = useS("All areas");
  const [ratingFilter, setRatingFilter] = useS("All ratings");
  const [healthFilter, setHealthFilter] = useS("All health");
  const [sortBy,    setSortBy]  = useS("joined");  // default: newest first
  const [sortDir,   setSortDir] = useS("desc");
  const [localSearch, setLocalSearch] = useS("");  // Local search within view
  const showTestData = useShowTestData();  // global toggle
  const [showFilters, setShowFilters] = useS(false);  // Toggle filter panel
  const [, setTick] = useS(0);  // Force re-render when test accounts change
  const PER_PAGE = 50;

  // Listen for test account changes
  React.useEffect(() => {
    const handleTestChange = () => setTick(t => t+1);
    window.addEventListener("testAccountsChanged", handleTestChange);
    return () => window.removeEventListener("testAccountsChanged", handleTestChange);
  }, []);

  const HEALTH_LABELS = { great:"Top chef", good:"Good", growing:"Growing", inactive:"Inactive", new:"New" };

  // Filter test accounts when in "Live" mode
  const allChefs = useMemo(() => {
    // Chefs page = the APPROVED network only (Active/Paused).
    // Pending / Rejected / Incomplete live on the Applications screen.
    let chefsList = (chefs || []).filter(c => c.status === "Active" || c.status === "Paused");
    if (!showTestData && window.BC_testAccounts) {
      chefsList = chefsList.filter(c => !window.BC_testAccounts.isTestChef(c.docId));
    }
    return chefsList;
  }, [chefs, showTestData]);

  // Unique areas for filter
  const areas = useMemo(() => {
    const s = new Set(allChefs.map(c=>c.area).filter(Boolean));
    return ["All areas", ...Array.from(s).sort()];
  }, [allChefs]);

  const totalActive  = allChefs.filter(c=>c.status==="Active").length;
  const totalPaused  = allChefs.filter(c=>c.status==="Paused").length;
  const pendingCount = (window.BC.northStar && window.BC.northStar.pending) || 0;
  const totalOrders  = allChefs.reduce((s,c)=>s+c.orders,0);
  const totalGMV     = allChefs.reduce((s,c)=>s+c.gmv,0);
  const avgRating    = (() => {
    const rated = allChefs.filter(c=>c.rating);
    return rated.length ? (rated.reduce((s,c)=>s+parseFloat(c.rating),0)/rated.length).toFixed(1) : "—";
  })();
  const topChef = allChefs.filter(c=>c.status==="Active").sort((a,b)=>b.orders-a.orders)[0];

  // Sort helpers
  function sortVal(c) {
    if (sortBy==="gmv")    return c.gmv || 0;
    if (sortBy==="rating") return parseFloat(c.rating) || 0;
    if (sortBy==="joined") return tsMs(c.joinedAt);
    return c.orders || 0;
  }

  function matchRating(c) {
    if (ratingFilter==="All ratings") return true;
    if (ratingFilter==="Unrated")     return !c.rating;
    const r = parseFloat(c.rating) || 0;
    if (ratingFilter==="4.5+ ★")      return r >= 4.5;
    if (ratingFilter==="4.0+ ★")      return r >= 4.0;
    if (ratingFilter==="3.0+ ★")      return r >= 3.0;
    if (ratingFilter==="Below 3.0")   return c.rating && r < 3.0;
    return true;
  }

  const filtered = useMemo(() =>
    allChefs.filter(c =>
      (status==="All" || c.status===status) &&
      (areaFilter==="All areas" || c.area===areaFilter) &&
      (healthFilter==="All health" || HEALTH_LABELS[c.health]===healthFilter) &&
      matchRating(c) &&
      (!query || (c.name+c.area+c.id+c.mobile+(c.email||"")).toLowerCase().includes(query.toLowerCase())) &&
      (!localSearch || (c.name+c.area+c.id+c.mobile+(c.email||"")).toLowerCase().includes(localSearch.toLowerCase()))
    ).sort((a,b) => sortDir==="desc" ? sortVal(b)-sortVal(a) : sortVal(a)-sortVal(b)),
    [allChefs, status, areaFilter, ratingFilter, healthFilter, query, sortBy, sortDir, localSearch]
  );

  const paged   = filtered.slice(0, (page+1)*PER_PAGE);
  const hasMore = filtered.length > paged.length;

  function toggleSort(col) {
    if (sortBy===col) setSortDir(d=>d==="desc"?"asc":"desc");
    else { setSortBy(col); setSortDir("desc"); }
    setPage(0);
  }

  function SortIcon({ col }) {
    if (sortBy!==col) return <span style={{opacity:.3,fontSize:10}}>⇅</span>;
    return <span style={{color:"var(--c-primary-text)",fontSize:10}}>{sortDir==="desc"?"↓":"↑"}</span>;
  }

  // ── CSV export ──
  // Exports respect the same data-visibility permissions as the screen —
  // a column you can't see in the table never makes it into the file either.
  function exportCSV() {
    const showFinancials = can("sensitive","viewFinancials");
    const showPayouts    = can("sensitive","viewPayouts");
    const showContact    = can("sensitive","viewContactInfo");
    const cols = ["Name","ID","Area",
                  ...(showContact ? ["Mobile","Email"] : []),
                  "Kitchen","Status","Health","Orders",
                  ...(showFinancials ? ["GMV (EGP)","Avg Order (EGP)"] : []),
                  ...(showPayouts ? ["Chef Earned (EGP)"] : []),
                  "Rating","Categories","Joined"];
    const rows = filtered.map(c => {
      const chefEarned = (window.BC.orders||[])
        .filter(o=>o.chefId===c.docId && o.paid)
        .reduce((s,o)=>s+(o.value-o.fee),0);
      return [
        c.name, c.id, c.area,
        ...(showContact ? [c.mobile||"", c.email||""] : []),
        c.kitchenName||"", c.status, c.health, c.orders,
        ...(showFinancials ? [c.gmv, c.orders>0?Math.round(c.gmv/c.orders):""] : []),
        ...(showPayouts ? [chefEarned] : []),
        c.rating||"", (c.categories||[]).join(" | "), c.joined,
      ].map(v=>`"${String(v||"").replace(/"/g,'""')}"`);
    });
    const csv = [cols.join(","), ...rows.map(r=>r.join(","))].join("\n");
    const blob = new Blob(["﻿"+csv], {type:"text/csv;charset=utf-8"});
    const url  = URL.createObjectURL(blob);
    const a    = document.createElement("a");
    a.href = url;
    a.download = `betychef-chefs-${status.toLowerCase().replace(/\s/g,"-")}-${new Date().toISOString().slice(0,10)}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  }

  return (
    <div className="bc-stack">

      {/* ── Quick search ── */}
      <input
        className="bc-input"
        type="text"
        placeholder="🔍 Search chefs by name, ID, area, email..."
        value={localSearch}
        onChange={e => {setLocalSearch(e.target.value); setPage(0);}}
        style={{padding:"10px 14px", fontSize:"14px"}}
      />

      {/* ── Quick stats ── */}
      <div className="bc-chef-stats-grid">
        <div className="bc-chef-stat-card bc-chef-stat-card--total"
          onClick={()=>{setStatus("All");setPage(0);}} style={{cursor:"pointer"}}>
          <div className="bc-cstat-num">{allChefs.length}</div>
          <div className="bc-cstat-label">Total chefs</div>
          <div className="bc-cstat-sub">on the platform</div>
        </div>
        <div className="bc-chef-stat-card bc-chef-stat-card--active"
          onClick={()=>{setStatus("Active");setPage(0);}} style={{cursor:"pointer"}}>
          <div className="bc-cstat-dot" style={{background:"var(--c-green)"}}/>
          <div className="bc-cstat-num" style={{color:"var(--c-green)"}}>{totalActive}</div>
          <div className="bc-cstat-label">Active</div>
          <div className="bc-cstat-sub">live on the app</div>
        </div>
        <div className="bc-chef-stat-card bc-chef-stat-card--joined"
          onClick={()=>navigate && navigate("applications")} style={{cursor:"pointer"}}>
          <div className="bc-cstat-dot" style={{background:"var(--c-saffron)"}}/>
          <div className="bc-cstat-num" style={{color:"#7a6800"}}>{pendingCount}</div>
          <div className="bc-cstat-label">Pending applications</div>
          <div className="bc-cstat-sub">{pendingCount > 0 ? "tap to review →" : "all reviewed"}</div>
        </div>
        <div className="bc-chef-stat-card bc-chef-stat-card--paused"
          onClick={()=>{setStatus("Paused");setPage(0);}} style={{cursor:"pointer"}}>
          <div className="bc-cstat-dot" style={{background:"var(--c-line-2)"}}/>
          <div className="bc-cstat-num">{totalPaused}</div>
          <div className="bc-cstat-label">Offline</div>
          <div className="bc-cstat-sub">paused by you or them</div>
        </div>
        <div className="bc-chef-stat-card">
          <div className="bc-cstat-num">{totalOrders.toLocaleString()}</div>
          <div className="bc-cstat-label">Total orders</div>
          <div className="bc-cstat-sub">across all chefs</div>
        </div>
        <div className="bc-chef-stat-card">
          <div className="bc-cstat-num"><Gate need="sensitive" action="viewFinancials">{egpK(totalGMV)}</Gate></div>
          <div className="bc-cstat-label">Total GMV</div>
          <div className="bc-cstat-sub">all time</div>
        </div>
        {topChef && (
          <div className="bc-chef-stat-card bc-chef-stat-card--top"
            onClick={()=>setActive(topChef)} style={{cursor:"pointer",gridColumn:"span 2"}}>
            <div style={{display:"flex",alignItems:"center",gap:10}}>
              <Avatar name={topChef.name} photoUrl={topChef.kitchenImage||null}/>
              <div>
                <div className="bc-cstat-label" style={{marginBottom:2}}>⭐ Top chef</div>
                <div className="bc-cstat-num" style={{fontSize:18}}>{topChef.name}</div>
                <div className="bc-cstat-sub">{topChef.orders} orders · <Gate need="sensitive" action="viewFinancials">{egpK(topChef.gmv)} GMV</Gate></div>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* ── Toolbar ── */}
      {pendingCount > 0 && (
        <div className="bc-actionbar">
          <span><Icon name="verify" size={18}/>
            <b>{pendingCount} application{pendingCount!==1?"s":""}</b> waiting for your review
          </span>
          <button className="bc-btn bc-btn--primary bc-btn--sm" onClick={()=>navigate && navigate("applications")}>
            Review now →
          </button>
        </div>
      )}

      {/* ── Actions toolbar ── */}
      <div className="bc-toolbar">
        <div className="bc-toolbar-right">
          <button className="bc-btn bc-tooltip" onClick={()=>setShowFilters(!showFilters)} data-tooltip={showFilters?"Hide filters":"Show filters"} style={{background:"var(--c-surface-2)",fontWeight:600}}>
            <Icon name={showFilters?"chevron-up":"sliders"} size={16}/>
          </button>
          {can("analytics","export") && (
            <button className="bc-btn bc-tooltip" onClick={exportCSV} data-tooltip="Download all chefs as CSV">
              <Icon name="download" size={16}/>Export
            </button>
          )}
          {can("chefs","approve") && (
            <button className="bc-btn bc-btn--primary bc-tooltip" onClick={()=>setAddOpen(true)} data-tooltip="Register a new chef">
              <Icon name="plus" size={16} stroke={2.2}/>Add chef
            </button>
          )}
        </div>
      </div>

      {/* ── Collapsible filters panel ── */}
      {showFilters && (
        <div className="bc-toolbar" style={{paddingTop:0,borderTop:"1px solid var(--c-line)"}}>
          <div style={{display:"flex",gap:12,flexWrap:"wrap",width:"100%"}}>
            <select className="bc-select" value={areaFilter} onChange={e=>{setAreaFilter(e.target.value);setPage(0);}}>
              {areas.map(a=><option key={a}>{a}</option>)}
            </select>
            <select className="bc-select" value={ratingFilter} onChange={e=>{setRatingFilter(e.target.value);setPage(0);}}>
              {["All ratings","4.5+ ★","4.0+ ★","3.0+ ★","Below 3.0","Unrated"].map(r=><option key={r}>{r}</option>)}
            </select>
            <select className="bc-select" value={healthFilter} onChange={e=>{setHealthFilter(e.target.value);setPage(0);}}>
              {["All health","Top chef","Good","Growing","Inactive","New"].map(h=><option key={h}>{h}</option>)}
            </select>
            <select className="bc-select" value={sortBy+"-"+sortDir} onChange={e=>{const [b,d]=e.target.value.split("-");setSortBy(b);setSortDir(d);setPage(0);}}>
              <option value="joined-desc">Newest first</option>
              <option value="joined-asc">Oldest first</option>
              <option value="orders-desc">Most orders</option>
              <option value="orders-asc">Fewest orders</option>
              <option value="gmv-desc">Highest GMV</option>
              <option value="gmv-asc">Lowest GMV</option>
              <option value="rating-desc">Top rated</option>
              <option value="rating-asc">Lowest rated</option>
            </select>
            {(status!=="All"||areaFilter!=="All areas"||ratingFilter!=="All ratings"||healthFilter!=="All health"||sortBy!=="joined"||sortDir!=="desc") && (
              <button className="bc-btn" onClick={()=>{setStatus("All");setAreaFilter("All areas");setRatingFilter("All ratings");setHealthFilter("All health");setSortBy("joined");setSortDir("desc");setPage(0);}}>
                <Icon name="x" size={15}/>Clear
              </button>
            )}
          </div>
        </div>
      )}

      {/* ── Result count ── */}
      <div className="bc-result-bar">
        Showing <b>{filtered.length}</b> chef{filtered.length!==1?"s":""}
        {status!=="All" && <> · <span className="bc-result-tag">{status}</span></>}
        {areaFilter!=="All areas" && <> · <span className="bc-result-tag">{areaFilter}</span></>}
        {ratingFilter!=="All ratings" && <> · <span className="bc-result-tag">{ratingFilter}</span></>}
        {healthFilter!=="All health" && <> · <span className="bc-result-tag">{healthFilter}</span></>}
        {query && <> · matching "<b>{query}</b>"</>}
      </div>

      <div className="bc-card" style={{padding:0,overflow:"hidden"}}>
        <div style={{overflowX:"auto"}}>
          <table className="bc-table bc-table--analytics">
            <thead>
              <tr>
                <th style={{minWidth:190}}>Chef</th>
                <th>Area</th>
                <th>Status</th>
                <th>Health</th>
                <th className="num bc-th-sort" onClick={()=>toggleSort("orders")}>Orders <SortIcon col="orders"/></th>
                <th className="num bc-th-sort" onClick={()=>toggleSort("gmv")}>GMV <SortIcon col="gmv"/></th>
                <th className="num">Chef earned</th>
                <th className="num">Avg order</th>
                <th className="num bc-th-sort" onClick={()=>toggleSort("rating")}>Rating <SortIcon col="rating"/></th>
                <th>Joined</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {paged.map(c=>{
                const earned = (window.BC.orders||[])
                  .filter(o=>o.chefId===c.docId && o.paid)
                  .reduce((s,o)=>s+(o.value-o.fee),0);
                const avgOrder = c.orders>0 ? Math.round(c.gmv/c.orders) : 0;
                return (
                  <tr key={c.docId} onClick={()=>setActive(c)} style={{cursor:"pointer"}}>
                    <td>
                      <div className="bc-recipe-cell">
                        <Avatar name={c.name} photoUrl={c.kitchenImage||null}/>
                        <div>
                          <div style={{display:"flex",alignItems:"center",gap:8}}>
                            <div className="bc-recipe-name">{c.name}</div>
                            {window.BC_testAccounts && window.BC_testAccounts.isTestChef(c.docId) && (
                              <span style={{
                                background:"var(--c-primary)",
                                color:"#fff",
                                fontSize:10,
                                fontWeight:700,
                                padding:"2px 8px",
                                borderRadius:4,
                                whiteSpace:"nowrap"
                              }}>TEST</span>
                            )}
                          </div>
                          <div className="bc-recipe-id">{c.id}</div>
                        </div>
                      </div>
                    </td>
                    <td className="bc-muted-cell">
                      <span className="bc-area-tag"><Icon name="pin" size={12}/>{c.area}</span>
                    </td>
                    <td><Pill status={c.status}/></td>
                    <td><HealthBadge health={c.health}/></td>
                    <td className="num bc-strong">{c.orders||"—"}</td>
                    <td className="num"><Gate need="sensitive" action="viewFinancials">{c.gmv?egpK(c.gmv):"—"}</Gate></td>
                    <td className="num" style={{color:"var(--c-primary-text)"}}><Gate need="sensitive" action="viewPayouts">{earned?egpK(earned):"—"}</Gate></td>
                    <td className="num bc-muted-cell"><Gate need="sensitive" action="viewFinancials">{avgOrder?egp(avgOrder):"—"}</Gate></td>
                    <td className="num">
                      {c.rating
                        ? <span className="bc-rating"><Icon name="star" size={12} stroke={0} fill="var(--c-saffron)"/>{c.rating}</span>
                        : <span className="bc-muted-cell">—</span>}
                    </td>
                    <td className="bc-muted-cell" style={{whiteSpace:"nowrap"}}>{c.joined}</td>
                    <td><Icon name="chevron" size={16} style={{opacity:.4}}/></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
        {filtered.length===0 && <div className="bc-empty">No chefs match these filters.</div>}
        {hasMore && (
          <div style={{padding:"14px 20px",borderTop:"1px solid var(--c-line)"}}>
            <button className="bc-btn" style={{width:"100%"}} onClick={()=>setPage(p=>p+1)}>
              Show more ({filtered.length - paged.length} remaining)
            </button>
          </div>
        )}
      </div>

      <Modal open={!!active} onClose={()=>setActive(null)} title={active?.name||""} wide>
        {active && <ChefDetail c={active} onClose={()=>setActive(null)}/>}
      </Modal>
      <Modal open={addOpen} onClose={()=>setAddOpen(false)} title="Add new chef" wide>
        <AddChefForm onClose={()=>setAddOpen(false)}/>
      </Modal>
    </div>
  );
}

/* ── Chef Detail ── */
function ChefDetail({ c, onClose }) {
  const { can } = usePermissions();
  const [status,        setStatus]        = useS(c.status);
  const [tab,           setTab]           = useS("info");
  const [saving,        setSaving]        = useS(false);
  const [msg,           setMsg]           = useS("");
  const [confirmRemove, setConfirmRemove] = useS(false);
  const [isTestAccount, setIsTestAccount] = useS(window.BC_testAccounts ? window.BC_testAccounts.isTestChef(c.docId) : false);

  const chefOrders   = useMemo(() => (window.BC.orders||[]).filter(o => o.chefId===c.docId).slice(0,30), [c.docId]);
  const chefEarned   = chefOrders.reduce((s,o) => s + (o.value - o.fee), 0);

  const statusColor  = status==="Active" ? "var(--c-green)" : status==="Paused" ? "#C2410C" : "var(--c-saffron)";
  const statusLabel  = status==="Active" ? "Online — live on the app" : status==="Paused" ? "Offline — hidden from customers" : "Awaiting activation";

  async function activate()     { setSaving(true); try { await window.BC_actions.approveChef(c.docId);    setStatus("Active"); setMsg("✓ Now live on the app"); } catch(e){setMsg(e.message);} setSaving(false); }
  async function goOffline()    { setSaving(true); try { await window.BC_actions.pauseChef(c.docId);      setStatus("Paused"); setMsg("Chef is offline");        } catch(e){setMsg(e.message);} setSaving(false); }
  async function bringOnline()  { setSaving(true); try { await window.BC_actions.reactivateChef(c.docId); setStatus("Active"); setMsg("✓ Back online");          } catch(e){setMsg(e.message);} setSaving(false); }
  async function removeChef()   { try { await window.BC_actions.deleteChef(c.docId); onClose(); } catch(e){setMsg(e.message); setConfirmRemove(false);} }
  async function sendNotify()   {
    const title = prompt("Notification title:"); if(!title) return;
    const body  = prompt("Message:");            if(!body)  return;
    try { await window.BC_actions.sendNotification({title,body,target:"specific",targetIds:[c.docId]}); setMsg("Notification sent ✓"); } catch(e){setMsg(e.message);}
  }

  function toggleTestAccount() {
    if (window.BC_testAccounts) {
      window.BC_testAccounts.toggleChef(c.docId);
      setIsTestAccount(!isTestAccount);
      setMsg(isTestAccount ? "Removed from test accounts" : "✓ Marked as test account");
    }
  }

  /* ── info rows: only show rows that have data ── */
  const infoRows = [
    c.area        && { label:"Area",           value: c.area },
    c.mobile      && { label:"Mobile",         value: c.mobile, need:"viewContactInfo" },
    c.email       && { label:"Email",          value: c.email, need:"viewContactInfo" },
    c.kitchenName && { label:"Kitchen",        value: c.kitchenName },
    c.workHours   && { label:"Working hours",  value: c.workHours },
    c.capacity    && { label:"Daily capacity", value: c.capacity + " orders/day" },
    c.joined      && { label:"Joined",         value: c.joined },
    c.instaPay    && { label:"InstaPay",       value: c.instaPay, need:"viewPayouts" },
  ].filter(Boolean);
  const showContact = can("sensitive","viewContactInfo");

  return (
    <div className="bc-detail-modal">

      {/* ── Header ── */}
      <div className="bc-detail-header">
        <div className="bc-detail-avatar" style={{background:"color-mix(in srgb,var(--c-green) 20%,transparent)"}}>
          {c.name.charAt(0).toUpperCase()}
        </div>
        <div className="bc-detail-header-info">
          <div className="bc-detail-header-title">{c.name}</div>
          <div className="bc-detail-header-sub" style={{color:statusColor}}>{statusLabel}</div>
        </div>
        <div className="bc-detail-header-actions">
          {isTestAccount && <span style={{background:"var(--c-primary)",color:"#fff",fontSize:10,fontWeight:700,padding:"4px 8px",borderRadius:6,whiteSpace:"nowrap"}}>TEST</span>}
          {status === "Active" && <HealthBadge health={c.health}/>}
        </div>
      </div>

      {/* ── STATS BAND ── */}
      <div className="bc-detail-stats-band">
        <div className="bc-detail-stat-item">
          <div className="bc-detail-stat-value">{c.orders||0}</div>
          <div className="bc-detail-stat-label">Orders</div>
        </div>
        <div className="bc-detail-stat-item">
          <div className="bc-detail-stat-value"><Gate need="sensitive" action="viewFinancials">{c.gmv?egpK(c.gmv):"—"}</Gate></div>
          <div className="bc-detail-stat-label">GMV</div>
        </div>
        <div className="bc-detail-stat-item">
          <div className="bc-detail-stat-value"><Gate need="sensitive" action="viewPayouts">{chefEarned?egpK(chefEarned):"—"}</Gate></div>
          <div className="bc-detail-stat-label">Earned</div>
        </div>
        <div className="bc-detail-stat-item">
          <div className="bc-detail-stat-value">{c.rating ? <>{c.rating} <Icon name="star" size={12} stroke={0} fill="var(--c-saffron)" style={{verticalAlign:"middle"}}/></> : "—"}</div>
          <div className="bc-detail-stat-label">Rating</div>
        </div>
      </div>

      {/* ── TABS ── */}
      <div className="bc-detail-tabs">
        {[{id:"info",label:"Profile"},{id:"orders",label:"Orders",n:chefOrders.length},{id:"ratings",label:"Ratings"}].map(t=>(
          <button key={t.id} className={"bc-detail-tab"+(tab===t.id?" is-active":"")} onClick={()=>setTab(t.id)}>
            {t.label}{t.n>0&&<span style={{marginLeft:6,fontSize:11,opacity:.7}}>({t.n})</span>}
          </button>
        ))}
      </div>

      {/* ── TAB BODY ── */}
      <div className="bc-detail-body">

        {tab==="info" && (
          <>
            {infoRows.length > 0
              ? <>
                  {infoRows.map((r,i) => (
                    <div key={i} className="bc-detail-info-row">
                      <span className="bc-detail-info-label">{r.label}</span>
                      <span className="bc-detail-info-value">{r.need ? <Gate need="sensitive" action={r.need}>{r.value}</Gate> : r.value}</span>
                    </div>
                  ))}
                </>
              : <p style={{textAlign:"center",color:"var(--c-ink-2)",padding:"20px"}}>No profile info yet — the chef will fill this in through the app.</p>
            }
            {c.bio && <div style={{marginTop:16,paddingTop:16,borderTop:"1px solid var(--c-line)"}}><p style={{fontSize:13,color:"var(--c-ink-2)"}}>{c.bio}</p></div>}
            {(c.categories||[]).length > 0 && (
              <div style={{marginTop:16,paddingTop:16,borderTop:"1px solid var(--c-line)"}}>
                <p style={{fontSize:11,fontWeight:700,color:"var(--c-ink-2)",textTransform:"uppercase",marginBottom:10}}>Categories</p>
                <div className="bc-detail-tags">{c.categories.map(d=><Tag key={d}>{d}</Tag>)}</div>
              </div>
            )}
          </>
        )}

        {tab==="orders" && (
          chefOrders.length === 0
            ? <p style={{textAlign:"center",color:"var(--c-ink-2)",padding:"20px"}}>No orders yet.</p>
            : <table className="bc-table" style={{marginTop:0}}>
                <thead><tr>
                  <th>Order</th><th>Customer</th>
                  <th className="num">Value</th><th className="num">Your cut</th>
                  <th>Status</th>
                </tr></thead>
                <tbody>
                  {chefOrders.map(o=>(
                    <tr key={o.docId}>
                      <td className="bc-strong">{o.id}</td>
                      <td className="bc-muted-cell">{o.customer}</td>
                      <td className="num bc-strong">{egp(o.value)}</td>
                      <td className="num" style={{color:"var(--c-primary-text)",fontWeight:700}}><Gate need="sensitive" action="viewFinancials">{egp(o.fee)}</Gate></td>
                      <td><Pill status={o.status} sm/></td>
                    </tr>
                  ))}
                </tbody>
              </table>
        )}

        {tab==="ratings" && (
          <>
            <div style={{textAlign:"center",padding:"20px"}}>
              <div style={{fontSize:32,fontWeight:700,color:"var(--c-primary-text)"}}>{c.rating||"—"}</div>
              <div style={{fontSize:12,color:"var(--c-ink-2)",marginTop:4}}>avg rating · {c.orders||0} orders</div>
            </div>
            <p style={{textAlign:"center",color:"var(--c-ink-2)",paddingTop:20,borderTop:"1px solid var(--c-line)"}}>Customer reviews will appear here once orders come in.</p>
          </>
        )}
      </div>

      {/* ── FOOTER: Mark as test + Status actions ── */}
      {!confirmRemove ? (
        <div className="bc-detail-footer" style={{flexWrap:"wrap"}}>
          {msg && <div style={{width:"100%",padding:"10px 12px",background:"var(--c-surface-2)",borderRadius:8,fontSize:12,color:"var(--c-primary-text)",marginBottom:10,textAlign:"center"}}>{msg}</div>}

          <button className="bc-btn" onClick={toggleTestAccount} style={{flex:status==="Joined"||status==="Paused"?"1":""}}>
            {isTestAccount ? "✓ Test Account" : "Mark as test"}
          </button>

          {status==="Joined" && can("chefs","approve") && (
            <button className="bc-btn bc-btn--primary" onClick={activate} disabled={saving} style={{flex:1}}>
              <Icon name="check" size={14}/>{saving?"…":"Approve"}
            </button>
          )}
          {status==="Active" && can("chefs","pause") && (
            <button className="bc-btn" onClick={goOffline} disabled={saving} style={{flex:1}}>
              <Icon name="pause" size={14}/>{saving?"…":"Go offline"}
            </button>
          )}
          {status==="Paused" && can("chefs","pause") && (
            <button className="bc-btn bc-btn--primary" onClick={bringOnline} disabled={saving} style={{flex:1}}>
              <Icon name="check" size={14}/>{saving?"…":"Bring online"}
            </button>
          )}

          {can("notifications","send") && (
            <button className="bc-btn" onClick={sendNotify} style={{flex:1}}>
              <Icon name="notify" size={14}/>Notify
            </button>
          )}

          {can("chefs","delete") && (
            <button className="bc-btn bc-btn--danger" onClick={()=>setConfirmRemove(true)} style={{flex:1}}>
              <Icon name="trash" size={14}/>Remove
            </button>
          )}
        </div>
      ) : (
        <div className="bc-detail-footer" style={{flexDirection:"column"}}>
          <p style={{fontSize:14,fontWeight:600,marginBottom:8}}>⚠️ Remove {c.name} permanently?</p>
          <p style={{fontSize:12,color:"var(--c-ink-2)",marginBottom:12}}>Deletes them from BetyChef and the app instantly. Cannot be undone.</p>
          <div style={{display:"flex",gap:10}}>
            <button className="bc-btn" onClick={()=>setConfirmRemove(false)} style={{flex:1}}>Cancel</button>
            <button className="bc-btn bc-btn--danger" onClick={removeChef} style={{flex:1}}><Icon name="trash" size={12}/>Yes, remove</button>
          </div>
        </div>
      )}
    </div>
  );
}

/* ── Add Chef form ── */
// Exact categories from the app's chef registration screen
const CHEF_CATEGORIES = [
  "🫕 Egyptian", "🥗 Vegan", "🍰 Desserts",
  "🥩 Grills", "🍝 Pasta", "🍳 Breakfast",
  "🍲 Soups", "🦐 Seafood",
];

function AddChefForm({ onClose }) {
  const [form, setForm] = useS({
    fullName:"", email:"", phone:"",
    kitchenName:"", bio:"", address:"",
    workFrom:"", workTo:"", instaPay:"", nationalId:"",
  });
  const [cats,   setCats]   = useS([]);
  const [custom, setCustom] = useS("");
  const [saving, setSaving] = useS(false);
  const [err,    setErr]    = useS("");
  const set = k => e => setForm(f=>({...f,[k]:e.target.value}));

  function toggleCat(c) {
    setCats(prev => prev.includes(c) ? prev.filter(x=>x!==c) : [...prev, c]);
  }
  function addCustom() {
    const v = custom.trim();
    if (v && !cats.includes(v)) setCats(prev=>[...prev, v]);
    setCustom("");
  }

  async function submit(e) {
    e.preventDefault();
    if (!form.fullName.trim()) return setErr("Full name is required");
    if (!form.phone.trim())    return setErr("Phone number is required");
    setSaving(true);
    try {
      await window.BC_actions.addChef({
        fullName:    form.fullName,
        email:       form.email,
        mobile:      form.phone,        // app stores phone as `mobile`
        kitchenName: form.kitchenName,
        bio:         form.bio,
        address:     form.address,
        workFrom:    form.workFrom,
        workTo:      form.workTo,
        instaPay:    form.instaPay,
        nationalId:  form.nationalId,
        categories:  cats,
      });
      onClose();
    } catch(e) { setErr(e.message); }
    setSaving(false);
  }

  return (
    <form onSubmit={submit} className="bc-compose-form bc-addchef-form">

      {/* PERSONAL INFO */}
      <div className="bc-addchef-section">👤 Personal info</div>
      <div className="bc-form-row">
        <label className="bc-field"><span className="bc-field-label">Full name *</span>
          <input className="bc-input" value={form.fullName} onChange={set("fullName")} placeholder="e.g. Nour Hassan" autoFocus/></label>
        <label className="bc-field"><span className="bc-field-label">Phone number *</span>
          <input className="bc-input" value={form.phone} onChange={set("phone")} placeholder="+20 1XX XXX XXXX"/></label>
      </div>
      <label className="bc-field"><span className="bc-field-label">Email address</span>
        <input className="bc-input" type="email" value={form.email} onChange={set("email")} placeholder="your@email.com"/></label>

      {/* KITCHEN */}
      <div className="bc-addchef-section">🍳 Tell us about the kitchen</div>
      <div className="bc-form-row">
        <label className="bc-field"><span className="bc-field-label">Kitchen / display name</span>
          <input className="bc-input" value={form.kitchenName} onChange={set("kitchenName")} placeholder="e.g. Nour's Home Kitchen"/></label>
        <label className="bc-field"><span className="bc-field-label">Kitchen address</span>
          <input className="bc-input" value={form.address} onChange={set("address")} placeholder="Street, Area, City"/></label>
      </div>
      <label className="bc-field"><span className="bc-field-label">Bio</span>
        <textarea className="bc-textarea" rows={3} value={form.bio} onChange={set("bio")}
          placeholder="About the chef, their cooking style, and what makes their food special…"/></label>

      {/* CATEGORIES */}
      <label className="bc-field">
        <span className="bc-field-label">Categories they cook</span>
        <div className="bc-cat-chips">
          {CHEF_CATEGORIES.map(c=>(
            <button type="button" key={c}
              className={"bc-cat-chip"+(cats.includes(c)?" is-on":"")}
              onClick={()=>toggleCat(c)}>{c}</button>
          ))}
          {cats.filter(c=>!CHEF_CATEGORIES.includes(c)).map(c=>(
            <button type="button" key={c} className="bc-cat-chip is-on" onClick={()=>toggleCat(c)}>
              {c} ✕
            </button>
          ))}
        </div>
        <div style={{display:"flex",gap:8,marginTop:8}}>
          <input className="bc-input" value={custom} onChange={e=>setCustom(e.target.value)}
            placeholder="Add a custom category…"
            onKeyDown={e=>{if(e.key==="Enter"){e.preventDefault();addCustom();}}}/>
          <button type="button" className="bc-btn" onClick={addCustom}>Add</button>
        </div>
      </label>

      {/* WORKING HOURS */}
      <div className="bc-addchef-section">🕐 Working hours</div>
      <div className="bc-form-row">
        <label className="bc-field"><span className="bc-field-label">From</span>
          <input className="bc-input" value={form.workFrom} onChange={set("workFrom")} placeholder="e.g. 11 AM"/></label>
        <label className="bc-field"><span className="bc-field-label">To</span>
          <input className="bc-input" value={form.workTo} onChange={set("workTo")} placeholder="e.g. 8 PM"/></label>
      </div>

      {/* PAYOUT */}
      <div className="bc-addchef-section">💳 Payout details</div>
      <div className="bc-form-row">
        <label className="bc-field"><span className="bc-field-label">InstaPay / wallet number</span>
          <input className="bc-input" value={form.instaPay} onChange={set("instaPay")} placeholder="+20 1XX XXX XXXX"/></label>
        <label className="bc-field"><span className="bc-field-label">National ID number</span>
          <input className="bc-input" value={form.nationalId} onChange={set("nationalId")} placeholder="14-digit national ID"/></label>
      </div>

      {err && <div className="bc-login-err">{err}</div>}
      <div className="bc-compose-actions">
        <button type="button" className="bc-btn" onClick={onClose}>Cancel</button>
        <button type="submit" className="bc-btn bc-btn--primary" disabled={saving}>
          <Icon name="plus" size={15}/>{saving?"Adding…":"Add chef"}
        </button>
      </div>
    </form>
  );
}

/* ══════════════════════════════ ORDERS ══════════════════════════════════ */
const PAY_LABELS = { paymob:"Paymob", instapay:"InstaPay", cash:"Cash on Delivery" };
function payKey(o){
  const m = (o.paymentMethod||"paymob").toLowerCase().replace(/[\s_]/g,"");
  return m.includes("instapay")?"instapay":m.includes("cash")?"cash":"paymob";
}

function OrdersView({ query }) {
  const { can } = usePermissions();
  const { orders, orderStatuses } = window.BC;
  const [status,   setStatus]   = useS("All");
  const [payFilter,setPayFilter]= useS("All payments");
  const [ratingFilter, setRatingFilter] = useS("All ratings");
  const [chefFilter, setChefFilter] = useS("All chefs");
  const [areaFilter, setAreaFilter] = useS("All areas");
  const [period,   setPeriod]   = useS("all");      // today | week | month | all
  const [sortBy,   setSortBy]   = useS("date");     // date | value | fee | rating | items
  const [sortDir,  setSortDir]  = useS("desc");
  const [detail,   setDetail]   = useS(null);
  const [page,     setPage]     = useS(0);
  const showTestData = useShowTestData();  // global toggle

  // Open an order's detail when arriving from global search
  React.useEffect(() => {
    function openPending() {
      const p = window.BC._pendingDetail;
      if (p && p.view === "orders") {
        const item = (window.BC.orders || []).find(o => o.docId === p.docId);
        if (item) setDetail(item);
        window.BC._pendingDetail = null;
      }
    }
    openPending();
    window.addEventListener("bc-open-detail", openPending);
    return () => window.removeEventListener("bc-open-detail", openPending);
  }, []);
  const [showFilters, setShowFilters] = useS(false);  // Collapsible filters
  const [, setTick] = useS(0);  // Force re-render when test accounts change
  const PER_PAGE = 50;

  // Listen for test account changes
  React.useEffect(() => {
    const handleTestChange = () => setTick(t => t+1);
    window.addEventListener("testAccountsChanged", handleTestChange);
    return () => window.removeEventListener("testAccountsChanged", handleTestChange);
  }, []);

  // Visible orders: hide orphans (deleted chef) always; hide test threads
  // unless TEST mode is on. Single source of truth in BC_testAccounts.
  const all = useMemo(() => {
    const list = orders || [];
    if (!window.BC_testAccounts) return list;
    return list.filter(o => window.BC_testAccounts.isOrderVisible(o, showTestData));
  }, [orders, showTestData]);

  const td  = ts => ts ? (ts.toDate?ts.toDate():new Date(ts)) : null;

  // Unique chefs + areas for filters
  const chefOptions = useMemo(()=>{
    const s = new Set(all.map(o=>o.chef).filter(Boolean));
    return ["All chefs", ...Array.from(s).sort()];
  }, [all]);
  const areaOptions = useMemo(()=>{
    const s = new Set(all.map(o=>o.chefArea).filter(Boolean));
    return ["All areas", ...Array.from(s).sort()];
  }, [all]);
  const orderRating = o => (window.BC._reviewsByOrder||{})[o.docId]?.rating || null;
  function matchRating(o){
    if (ratingFilter==="All ratings") return true;
    const r = orderRating(o);
    if (ratingFilter==="Unrated")   return !r;
    if (ratingFilter==="5 ★")       return r===5;
    if (ratingFilter==="4+ ★")      return r>=4;
    if (ratingFilter==="3+ ★")      return r>=3;
    if (ratingFilter==="Below 3 ★") return r && r<3;
    return true;
  }

  // Period cutoff
  const cutoff = useMemo(()=>{
    const now=new Date();
    if (period==="today"){const d=new Date(now);d.setHours(0,0,0,0);return d;}
    if (period==="week"){const d=new Date(now);d.setDate(d.getDate()-6);d.setHours(0,0,0,0);return d;}
    if (period==="month"){const d=new Date(now);d.setDate(1);d.setHours(0,0,0,0);return d;}
    return null;
  },[period]);

  function sortVal(o){
    if (sortBy==="value")  return o.value||0;
    if (sortBy==="fee")    return o.fee||0;
    if (sortBy==="rating") return orderRating(o)||0;
    if (sortBy==="items")  return o.itemCount||0;
    const d=td(o.createdAt); return d?d.getTime():0;
  }

  const filtered = useMemo(()=>
    all.filter(o =>
      (status==="All" || o.status===status) &&
      (payFilter==="All payments" || PAY_LABELS[payKey(o)]===payFilter) &&
      (chefFilter==="All chefs" || o.chef===chefFilter) &&
      (areaFilter==="All areas" || o.chefArea===areaFilter) &&
      matchRating(o) &&
      (!cutoff || (td(o.createdAt) && td(o.createdAt)>=cutoff)) &&
      (!query || (o.chef+o.customer+o.id).toLowerCase().includes(query.toLowerCase()))
    ).sort((a,b)=> sortDir==="desc" ? sortVal(b)-sortVal(a) : sortVal(a)-sortVal(b)),
    [all, status, payFilter, ratingFilter, chefFilter, areaFilter, period, query, sortBy, sortDir, window.BC._reviewsByOrder]
  );

  const paged   = filtered.slice(0,(page+1)*PER_PAGE);
  const hasMore = filtered.length > paged.length;
  const anyFilter = status!=="All"||payFilter!=="All payments"||ratingFilter!=="All ratings"||chefFilter!=="All chefs"||areaFilter!=="All areas"||period!=="all"||sortBy!=="date"||sortDir!=="desc";

  // Stats on the filtered set
  const fGmv     = filtered.filter(o=>o.paid).reduce((s,o)=>s+o.value,0);
  const fFees    = filtered.filter(o=>o.paid).reduce((s,o)=>s+o.fee,0);
  const fLive    = filtered.filter(o=>["New","Preparing","Ready","On the way"].includes(o.status)).length;
  const fDone    = filtered.filter(o=>o.status==="Delivered").length;
  const fCancel  = filtered.filter(o=>o.status==="Cancelled").length;
  const fAvg     = filtered.filter(o=>o.paid).length ? Math.round(fGmv/filtered.filter(o=>o.paid).length) : 0;

  function toggleSort(col){
    if (sortBy===col) setSortDir(d=>d==="desc"?"asc":"desc");
    else { setSortBy(col); setSortDir("desc"); }
    setPage(0);
  }
  function SortIcon({col}){
    if (sortBy!==col) return <span style={{opacity:.3,fontSize:10}}>⇅</span>;
    return <span style={{color:"var(--c-primary-text)",fontSize:10}}>{sortDir==="desc"?"↓":"↑"}</span>;
  }

  function fmtDate(ts){
    const d=td(ts); if(!d) return "—";
    return d.toLocaleDateString("en-GB",{day:"numeric",month:"short"})+" "+d.toLocaleTimeString("en-GB",{hour:"2-digit",minute:"2-digit"});
  }

  function exportCSV(){
    const showFinancials = can("sensitive","viewFinancials");
    const showPayouts    = can("sensitive","viewPayouts");
    const showContact    = can("sensitive","viewContactInfo");
    const cols=["Order ID","Chef","Chef Area","Customer","Items","Order Value (EGP)",
                ...(showFinancials ? ["Platform Fee (EGP)"] : []),
                ...(showPayouts ? ["Chef Earned (EGP)"] : []),
                "Status","Payment","Rating","Date",
                ...(showContact ? ["Delivery Address"] : [])];
    const rows=filtered.map(o=>[
      o.id, o.chef, o.chefArea||"", o.customer, o.itemCount, o.value,
      ...(showFinancials ? [o.fee] : []),
      ...(showPayouts ? [o.value-o.fee] : []),
      o.status, PAY_LABELS[payKey(o)], orderRating(o)||"", fmtDate(o.createdAt),
      ...(showContact ? [o.deliveryAddress||""] : []),
    ].map(v=>`"${String(v||"").replace(/"/g,'""')}"`));
    const csv=[cols.join(","),...rows.map(r=>r.join(","))].join("\n");
    const blob=new Blob(["﻿"+csv],{type:"text/csv;charset=utf-8"});
    const url=URL.createObjectURL(blob);
    const a=document.createElement("a");
    a.href=url; a.download=`betychef-orders-${period}-${new Date().toISOString().slice(0,10)}.csv`; a.click();
    URL.revokeObjectURL(url);
  }

  const PERIODS=[{value:"today",label:"Today"},{value:"week",label:"This week"},{value:"month",label:"This month"},{value:"all",label:"All time"}];

  return (
    <div className="bc-stack">

      {/* ── Period filter ── */}
      <div className="bc-segmented" style={{alignSelf:"flex-start"}}>
        {PERIODS.map(p=>(
          <button key={p.value} className={period===p.value?"is-active":""}
            onClick={()=>{setPeriod(p.value);setPage(0);}}>{p.label}</button>
        ))}
      </div>

      {/* ── Quick stats ── */}
      <div className="bc-chef-stats-grid">
        <div className="bc-chef-stat-card">
          <div className="bc-cstat-num">{filtered.length.toLocaleString()}</div>
          <div className="bc-cstat-label">Orders</div>
          <div className="bc-cstat-sub">{PERIODS.find(p=>p.value===period)?.label}</div>
        </div>
        <div className="bc-chef-stat-card">
          <div className="bc-cstat-dot" style={{background:"var(--c-saffron)"}}/>
          <div className="bc-cstat-num">{fLive}<span className="bc-livedot bc-livedot--lg" style={{marginLeft:6}}/></div>
          <div className="bc-cstat-label">In progress</div>
          <div className="bc-cstat-sub">live now</div>
        </div>
        <div className="bc-chef-stat-card">
          <div className="bc-cstat-dot" style={{background:"var(--c-green)"}}/>
          <div className="bc-cstat-num" style={{color:"var(--c-green)"}}>{fDone}</div>
          <div className="bc-cstat-label">Delivered</div>
          <div className="bc-cstat-sub">{fCancel} cancelled</div>
        </div>
        <div className="bc-chef-stat-card">
          <div className="bc-cstat-num"><Gate need="sensitive" action="viewFinancials">{egpK(fGmv)}</Gate></div>
          <div className="bc-cstat-label">GMV</div>
          <div className="bc-cstat-sub"><Gate need="sensitive" action="viewFinancials">avg {egp(fAvg)}/order</Gate></div>
        </div>
        <div className="bc-chef-stat-card bc-chef-stat-card--top" style={{gridColumn:"span 2"}}>
          <div className="bc-cstat-label" style={{marginBottom:4}}>💰 Your platform fees</div>
          <div className="bc-cstat-num" style={{color:"var(--c-primary-text)",fontSize:28}}><Gate need="sensitive" action="viewFinancials">{egp(fFees)}</Gate></div>
          <div className="bc-cstat-sub">from {filtered.filter(o=>o.paid).length} paid orders · auto-deducted</div>
        </div>
      </div>

      {/* ── Status + actions toolbar ── */}
      <div className="bc-toolbar">
        <div className="bc-segmented bc-segmented--scroll">
          {["All",...(orderStatuses||[])].map(s=>(
            <button key={s} className={status===s?"is-active":""} onClick={()=>{setStatus(s);setPage(0);}}>
              {s}<span className="bc-seg-count">{s==="All"?all.length:all.filter(o=>o.status===s).length}</span>
            </button>
          ))}
        </div>
        <div className="bc-toolbar-right">
          <button className="bc-btn bc-tooltip" onClick={()=>setShowFilters(!showFilters)} data-tooltip={showFilters?"Hide filters":"Show filters"} style={{background:"var(--c-surface-2)",fontWeight:600,padding:"10px 14px"}}>
            <Icon name={showFilters?"chevron-up":"sliders"} size={16}/>Filters
          </button>
          {can("analytics","export") && <button className="bc-btn" onClick={exportCSV}><Icon name="download" size={16}/>Export</button>}
        </div>
      </div>

      {/* ── Collapsible filters panel ── */}
      {showFilters && (
        <div className="bc-toolbar" style={{paddingTop:0}}>
          <div style={{display:"flex",gap:12,flexWrap:"wrap",width:"100%"}}>
            <select className="bc-select" value={chefFilter} onChange={e=>{setChefFilter(e.target.value);setPage(0);}}>
              {chefOptions.map(c=><option key={c}>{c}</option>)}
            </select>
            <select className="bc-select" value={areaFilter} onChange={e=>{setAreaFilter(e.target.value);setPage(0);}}>
              {areaOptions.map(a=><option key={a}>{a}</option>)}
            </select>
            <select className="bc-select" value={payFilter} onChange={e=>{setPayFilter(e.target.value);setPage(0);}}>
              {["All payments","Paymob","InstaPay","Cash on Delivery"].map(p=><option key={p}>{p}</option>)}
            </select>
            <select className="bc-select" value={ratingFilter} onChange={e=>{setRatingFilter(e.target.value);setPage(0);}}>
              {["All ratings","5 ★","4+ ★","3+ ★","Below 3 ★","Unrated"].map(r=><option key={r}>{r}</option>)}
            </select>
            <select className="bc-select" value={sortBy+"-"+sortDir} onChange={e=>{const[b,d]=e.target.value.split("-");setSortBy(b);setSortDir(d);setPage(0);}}>
              <option value="date-desc">Newest first</option>
              <option value="date-asc">Oldest first</option>
              <option value="value-desc">Highest value</option>
              <option value="value-asc">Lowest value</option>
              <option value="fee-desc">Highest fee</option>
              <option value="items-desc">Most items</option>
              <option value="rating-desc">Top rated</option>
            </select>
            {anyFilter && (
              <button className="bc-btn" onClick={()=>{setStatus("All");setPayFilter("All payments");setRatingFilter("All ratings");setChefFilter("All chefs");setAreaFilter("All areas");setPeriod("all");setSortBy("date");setSortDir("desc");setPage(0);}}>
                <Icon name="x" size={15}/>Clear
              </button>
            )}
          </div>
        </div>
      )}

      {/* ── Result bar ── */}
      <div className="bc-result-bar">
        Showing <b>{filtered.length}</b> order{filtered.length!==1?"s":""}
        {status!=="All" && <> · <span className="bc-result-tag">{status}</span></>}
        {chefFilter!=="All chefs" && <> · <span className="bc-result-tag">{chefFilter}</span></>}
        {areaFilter!=="All areas" && <> · <span className="bc-result-tag">{areaFilter}</span></>}
        {payFilter!=="All payments" && <> · <span className="bc-result-tag">{payFilter}</span></>}
        {ratingFilter!=="All ratings" && <> · <span className="bc-result-tag">{ratingFilter}</span></>}
        {period!=="all" && <> · <span className="bc-result-tag">{PERIODS.find(p=>p.value===period)?.label}</span></>}
        {query && <> · matching "<b>{query}</b>"</>}
      </div>

      {/* ── Table ── */}
      <div className="bc-card" style={{padding:0,overflow:"hidden"}}>
        <div style={{overflowX:"auto"}}>
          <table className="bc-table bc-table--analytics">
            <thead>
              <tr>
                <th>Order</th><th>Chef</th><th>Area</th><th>Customer</th>
                <th className="num">Items</th>
                <th className="num bc-th-sort" onClick={()=>toggleSort("value")}>Value <SortIcon col="value"/></th>
                <th className="num bc-th-sort" onClick={()=>toggleSort("fee")}>Your fee <SortIcon col="fee"/></th>
                <th>Payment</th>
                <th>Status</th>
                <th className="num bc-th-sort" onClick={()=>toggleSort("rating")}>Rating <SortIcon col="rating"/></th>
                <th className="bc-th-sort" onClick={()=>toggleSort("date")}>Date <SortIcon col="date"/></th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {paged.map(o=>{
                const rt = orderRating(o);
                return (
                <tr key={o.docId} className={o.status==="Cancelled"?"is-dim":""}
                  onClick={()=>setDetail(o)} style={{cursor:"pointer"}}>
                  <td>
                    <div style={{display:"flex",alignItems:"center",gap:8}}>
                      <span className="bc-strong">{o.id}</span>
                      {window.BC_testAccounts && (
                        (window.BC_testAccounts.isTestChef(o.chefId) || window.BC_testAccounts.isTestCustomer(o.customerId)) && (
                          <span style={{
                            background:"var(--c-primary)",
                            color:"#fff",
                            fontSize:9,
                            fontWeight:700,
                            padding:"1px 6px",
                            borderRadius:3,
                            whiteSpace:"nowrap"
                          }}>TEST</span>
                        )
                      )}
                    </div>
                  </td>
                  <td className="bc-muted-cell">{o.chef}</td>
                  <td className="bc-muted-cell" style={{whiteSpace:"nowrap"}}>{o.chefArea||"—"}</td>
                  <td className="bc-muted-cell">{o.customer}</td>
                  <td className="num bc-muted-cell">{o.itemCount}</td>
                  <td className="num bc-strong">{egp(o.value)}</td>
                  <td className="num"><span className="bc-fee"><Gate need="sensitive" action="viewFinancials">{egp(o.fee)}</Gate></span></td>
                  <td className="bc-muted-cell" style={{whiteSpace:"nowrap"}}>{PAY_LABELS[payKey(o)]}</td>
                  <td><Pill status={o.status} sm/></td>
                  <td className="num">{rt
                    ? <span className="bc-rating"><Icon name="star" size={12} stroke={0} fill="var(--c-saffron)"/>{rt}</span>
                    : <span className="bc-muted-cell">—</span>}</td>
                  <td className="bc-muted-cell" style={{whiteSpace:"nowrap"}}>{fmtDate(o.createdAt)}</td>
                  <td><Icon name="eye" size={14} style={{opacity:.4}}/></td>
                </tr>
                );
              })}
            </tbody>
          </table>
        </div>
        {filtered.length===0 && <div className="bc-empty">No orders match these filters.</div>}
        {hasMore && (
          <div style={{padding:"14px 20px",borderTop:"1px solid var(--c-line)"}}>
            <button className="bc-btn" style={{width:"100%"}} onClick={()=>setPage(p=>p+1)}>
              Show more ({filtered.length - paged.length} remaining)
            </button>
          </div>
        )}
      </div>

      <Modal open={!!detail} onClose={()=>setDetail(null)} title={"Order "+detail?.id} wide>
        {detail && <OrderDetail order={detail}/>}
      </Modal>
    </div>
  );
}

/* ── Order Detail popup ── */
function OrderDetail({ order: o }) {
  const { can } = usePermissions();
  const showFinancials = can("sensitive","viewFinancials");
  const showPayouts    = can("sensitive","viewPayouts");
  const showContact    = can("sensitive","viewContactInfo");
  return (
    <div className="bc-detail-modal">
      {/* Header */}
      <div className="bc-detail-header">
        <div className="bc-detail-avatar" style={{background:"color-mix(in srgb,var(--c-saffron) 20%,transparent)"}}>
          #
        </div>
        <div className="bc-detail-header-info">
          <div className="bc-detail-header-title">Order {o.id}</div>
          <div className="bc-detail-header-sub"><Pill status={o.status} sm/></div>
        </div>
      </div>

      {/* Money Flow */}
      <div className="bc-order-money-row">
        <div className="bc-order-money-box">
          <div className="bc-order-money-amt">{egp(o.value)}</div>
          <div className="bc-order-money-lbl">Order value</div>
        </div>
        <div className="bc-order-money-arrow">→</div>
        <div className="bc-order-money-box bc-order-money-box--fee">
          <div className="bc-order-money-amt">{showFinancials ? egp(o.fee) : <span className="bc-redacted"><Icon name="key" size={11}/>•••</span>}</div>
          <div className="bc-order-money-lbl">BetyChef fee</div>
        </div>
        <div className="bc-order-money-arrow">→</div>
        <div className="bc-order-money-box bc-order-money-box--chef">
          <div className="bc-order-money-amt">{showPayouts ? egp(o.value - o.fee) : <span className="bc-redacted"><Icon name="key" size={11}/>•••</span>}</div>
          <div className="bc-order-money-lbl">To chef</div>
        </div>
      </div>

      {/* Body */}
      <div className="bc-detail-body">
        <div className="bc-detail-info-row">
          <span className="bc-detail-info-label">Chef</span>
          <span className="bc-detail-info-value">{o.chef}</span>
        </div>
        <div className="bc-detail-info-row">
          <span className="bc-detail-info-label">Customer</span>
          <span className="bc-detail-info-value">{o.customer}</span>
        </div>
        <div className="bc-detail-info-row">
          <span className="bc-detail-info-label">Payment</span>
          <span className="bc-detail-info-value">{(o.paymentMethod||"paymob").replace(/_/g," ")}</span>
        </div>
        {o.deliveryAddress && showContact && (
          <div className="bc-detail-info-row">
            <span className="bc-detail-info-label">Delivery</span>
            <span className="bc-detail-info-value">{o.deliveryAddress}</span>
          </div>
        )}
        {o.notes && (
          <div className="bc-detail-info-row">
            <span className="bc-detail-info-label">Notes</span>
            <span className="bc-detail-info-value">{o.notes}</span>
          </div>
        )}

        {/* Items */}
        {(o.items||[]).length > 0 && (
          <div style={{marginTop:16,paddingTop:16,borderTop:"1px solid var(--c-line)"}}>
            <div style={{fontSize:12,fontWeight:700,color:"var(--c-ink-2)",textTransform:"uppercase",marginBottom:12}}>Items ({o.items.length})</div>
            {o.items.map((item,i)=>(
              <div key={i} className="bc-order-item-row">
                <span className="bc-order-item-name">{item.dishName||item.name||("Item "+(i+1))}</span>
                <span className="bc-order-item-qty">×{item.quantity||1}</span>
                <span className="bc-order-item-price bc-strong">{item.price?egp(item.price*(item.quantity||1)):""}</span>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Footer */}
      <div className="bc-detail-footer">
        <button className="bc-btn bc-btn--danger" onClick={async()=>{
          if(!window.confirm(`Delete Order #${o.id}? This cannot be undone.`)) return;
          try {
            await window.BC_actions.deleteOrder(o.docId);
            window.location.reload();
          } catch(e) {
            alert("Error deleting order: " + e.message);
          }
        }} style={{flex:1}}>
          <Icon name="trash" size={14}/> Delete
        </button>
      </div>
    </div>
  );
}

/* ══════════════════════════════ CUSTOMERS ═══════════════════════════════ */
function CustomersView({ query }) {
  const { can } = usePermissions();
  const { customers } = window.BC;
  const [detail,      setDetail]      = useS(null);
  const [typeFilter,  setTypeFilter]  = useS("All");          // All | Repeat | New
  const [areaFilter,  setAreaFilter]  = useS("All areas");

  // Open a customer's detail when arriving from global search
  React.useEffect(() => {
    function openPending() {
      const p = window.BC._pendingDetail;
      if (p && p.view === "customers") {
        const item = (window.BC.customers || []).find(c => c.docId === p.docId);
        if (item) setDetail(item);
        window.BC._pendingDetail = null;
      }
    }
    openPending();
    window.addEventListener("bc-open-detail", openPending);
    return () => window.removeEventListener("bc-open-detail", openPending);
  }, []);
  const [ratingFilter, setRatingFilter] = useS("All ratings");
  const [sortBy,      setSortBy]       = useS("joined");     // default: newest first
  const [sortDir,     setSortDir]     = useS("desc");
  const [page,        setPage]        = useS(0);
  const [localSearch, setLocalSearch] = useS("");  // Local search within view
  const showTestData = useShowTestData();  // global toggle
  const [showFilters, setShowFilters] = useS(false);  // Collapsible filters
  const [, setTick] = useS(0);  // Force re-render when test accounts change
  const PER_PAGE = 50;

  // Listen for test account changes
  React.useEffect(() => {
    const handleTestChange = () => setTick(t => t+1);
    window.addEventListener("testAccountsChanged", handleTestChange);
    return () => window.removeEventListener("testAccountsChanged", handleTestChange);
  }, []);

  // Filter test accounts when in "Live" mode
  const all = useMemo(() => {
    let customerList = customers || [];
    // Exclude test accounts when showTestData is false (LIVE DATA mode)
    if (!showTestData && window.BC_testAccounts) {
      customerList = customerList.filter(c => !window.BC_testAccounts.isTestCustomer(c.docId));
    }
    return customerList;
  }, [customers, showTestData]);

  // Avg rating a customer gives to chefs (from reviews)
  const custRating = c => {
    const a = (window.BC._reviewsByClient||{})[c.docId]?.avg;
    return a ? Number(a.toFixed(1)) : null;
  };
  function matchRating(c){
    if (ratingFilter==="All ratings")  return true;
    const r = custRating(c);
    if (ratingFilter==="Left reviews") return !!r;
    if (ratingFilter==="No reviews")   return !r;
    if (ratingFilter==="Gives 4+ ★")   return r && r>=4;
    if (ratingFilter==="Gives <3 ★")   return r && r<3;
    return true;
  }

  const areas = useMemo(()=>{
    const s = new Set(all.map(c=>c.area).filter(Boolean));
    return ["All areas", ...Array.from(s).sort()];
  }, [all]);

  // Quick stats
  const totalCust   = all.length;
  const repeatCount = all.filter(c=>c.repeat).length;
  const newCount    = totalCust - repeatCount;
  const repeatRate  = totalCust ? Math.round(repeatCount/totalCust*100) : 0;
  const totalRev    = all.reduce((s,c)=>s+c.spend,0);
  const avgSpend    = totalCust ? Math.round(totalRev/totalCust) : 0;
  const topCust     = [...all].sort((a,b)=>b.spend-a.spend)[0];

  function sortVal(c){
    if (sortBy==="joined")  return tsMs(c.joinedAt);
    if (sortBy==="spend")   return c.spend   || 0;
    if (sortBy==="reviews") return c.reviews || 0;
    if (sortBy==="rating")  return custRating(c) || 0;
    return c.orders || 0;
  }

  const filtered = useMemo(()=>
    all.filter(c =>
      (typeFilter==="All" || (typeFilter==="Repeat"?c.repeat:!c.repeat)) &&
      (areaFilter==="All areas" || c.area===areaFilter) &&
      matchRating(c) &&
      (!query || (c.name+c.area+(c.email||"")+(c.phone||"")).toLowerCase().includes(query.toLowerCase())) &&
      (!localSearch || (c.name+c.area+(c.email||"")+(c.phone||"")).toLowerCase().includes(localSearch.toLowerCase()))
    ).sort((a,b)=> sortDir==="desc" ? sortVal(b)-sortVal(a) : sortVal(a)-sortVal(b)),
    [all, typeFilter, areaFilter, ratingFilter, query, sortBy, sortDir, window.BC._reviewsByClient, localSearch]
  );

  const paged   = filtered.slice(0,(page+1)*PER_PAGE);
  const hasMore = filtered.length > paged.length;
  const anyFilter = typeFilter!=="All"||areaFilter!=="All areas"||ratingFilter!=="All ratings"||sortBy!=="joined"||sortDir!=="desc";

  function toggleSort(col){
    if (sortBy===col) setSortDir(d=>d==="desc"?"asc":"desc");
    else { setSortBy(col); setSortDir("desc"); }
    setPage(0);
  }
  function SortIcon({col}){
    if (sortBy!==col) return <span style={{opacity:.3,fontSize:10}}>⇅</span>;
    return <span style={{color:"var(--c-primary-text)",fontSize:10}}>{sortDir==="desc"?"↓":"↑"}</span>;
  }

  function exportCSV(){
    const showFinancials = can("sensitive","viewFinancials");
    const showContact    = can("sensitive","viewContactInfo");
    const cols = ["Name","Area",
                  ...(showContact ? ["Phone","Email"] : []),
                  "Orders",
                  ...(showFinancials ? ["Total Spent (EGP)","Avg Order (EGP)"] : []),
                  "Reviews","Avg Rating Given","Favourite Chef","Type","Last Order","Joined","Credits"];
    const rows = filtered.map(c=>[
      c.name, c.area,
      ...(showContact ? [c.phone||"", c.email||""] : []),
      c.orders,
      ...(showFinancials ? [c.spend, c.orders>0?Math.round(c.spend/c.orders):""] : []),
      c.reviews, custRating(c)||"",
      c.fav||"", c.repeat?"Repeat":"New", c.last, c.joined||"", c.credits||0,
    ].map(v=>`"${String(v||"").replace(/"/g,'""')}"`));
    const csv = [cols.join(","),...rows.map(r=>r.join(","))].join("\n");
    const blob = new Blob(["﻿"+csv],{type:"text/csv;charset=utf-8"});
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href=url; a.download=`betychef-customers-${new Date().toISOString().slice(0,10)}.csv`; a.click();
    URL.revokeObjectURL(url);
  }

  return (
    <div className="bc-stack">

      {/* ── Quick search ── */}
      <input
        className="bc-input"
        type="text"
        placeholder="🔍 Search customers by name, email, phone, area..."
        value={localSearch}
        onChange={e => {setLocalSearch(e.target.value); setPage(0);}}
        style={{padding:"10px 14px", fontSize:"14px"}}
      />

      {/* ── Quick stats ── */}
      <div className="bc-chef-stats-grid">
        <div className="bc-chef-stat-card" onClick={()=>{setTypeFilter("All");setPage(0);}} style={{cursor:"pointer"}}>
          <div className="bc-cstat-num">{totalCust.toLocaleString()}</div>
          <div className="bc-cstat-label">Total customers</div>
          <div className="bc-cstat-sub">registered in the app</div>
        </div>
        <div className="bc-chef-stat-card" onClick={()=>{setTypeFilter("Repeat");setPage(0);}} style={{cursor:"pointer"}}>
          <div className="bc-cstat-dot" style={{background:"var(--c-green)"}}/>
          <div className="bc-cstat-num" style={{color:"var(--c-green)"}}>{repeatCount}</div>
          <div className="bc-cstat-label">Repeat customers</div>
          <div className="bc-cstat-sub">{repeatRate}% repeat rate</div>
        </div>
        <div className="bc-chef-stat-card" onClick={()=>{setTypeFilter("New");setPage(0);}} style={{cursor:"pointer"}}>
          <div className="bc-cstat-dot" style={{background:"var(--c-saffron)"}}/>
          <div className="bc-cstat-num">{newCount}</div>
          <div className="bc-cstat-label">New customers</div>
          <div className="bc-cstat-sub">ordered once or less</div>
        </div>
        <div className="bc-chef-stat-card">
          <div className="bc-cstat-num">{egp(avgSpend)}</div>
          <div className="bc-cstat-label">Avg. lifetime spend</div>
          <div className="bc-cstat-sub">per customer</div>
        </div>
        <div className="bc-chef-stat-card">
          <div className="bc-cstat-num">{egpK(totalRev)}</div>
          <div className="bc-cstat-label">Total customer spend</div>
          <div className="bc-cstat-sub">all time</div>
        </div>
        {topCust && topCust.spend>0 && (
          <div className="bc-chef-stat-card bc-chef-stat-card--top"
            onClick={()=>setDetail(topCust)} style={{cursor:"pointer",gridColumn:"span 3"}}>
            <div style={{display:"flex",alignItems:"center",gap:10}}>
              <Avatar name={topCust.name} kind="cust"/>
              <div>
                <div className="bc-cstat-label" style={{marginBottom:2}}>⭐ Top spender</div>
                <div className="bc-cstat-num" style={{fontSize:18}}>{topCust.name}</div>
                <div className="bc-cstat-sub">{topCust.orders} orders · {egp(topCust.spend)} spent</div>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* ── Filters + actions ── */}
      <div className="bc-toolbar">
        <div className="bc-segmented bc-segmented--scroll">
          {["All","Repeat","New"].map(t=>(
            <button key={t} className={typeFilter===t?"is-active":""} onClick={()=>{setTypeFilter(t);setPage(0);}}>
              {t}{t!=="All" && <span className="bc-seg-count">{t==="Repeat"?repeatCount:newCount}</span>}
            </button>
          ))}
        </div>
        <div className="bc-toolbar-right" style={{gap:8}}>
          <button className="bc-btn bc-tooltip" onClick={()=>setShowFilters(!showFilters)} data-tooltip={showFilters?"Hide filters":"Show filters"} style={{background:"var(--c-surface-2)",fontWeight:600,padding:"10px 14px"}}>
            <Icon name={showFilters?"chevron-up":"sliders"} size={16}/>Filters
          </button>
          {can("analytics","export") && (
            <button className="bc-btn bc-tooltip" onClick={exportCSV} data-tooltip="Download all customers as CSV">
              <Icon name="download" size={16}/>Export
            </button>
          )}
        </div>
      </div>

      {/* ── Collapsible filters panel ── */}
      {showFilters && (
        <div className="bc-toolbar" style={{paddingTop:0}}>
          <div style={{display:"flex",gap:12,flexWrap:"wrap",width:"100%"}}>
            <select className="bc-select" value={areaFilter} onChange={e=>{setAreaFilter(e.target.value);setPage(0);}}>
              {areas.map(a=><option key={a}>{a}</option>)}
            </select>
            <select className="bc-select" value={ratingFilter} onChange={e=>{setRatingFilter(e.target.value);setPage(0);}}>
              {["All ratings","Gives 4+ ★","Gives <3 ★","Left reviews","No reviews"].map(r=><option key={r}>{r}</option>)}
            </select>
            <select className="bc-select" value={sortBy+"-"+sortDir} onChange={e=>{const [b,d]=e.target.value.split("-");setSortBy(b);setSortDir(d);setPage(0);}}>
              <option value="joined-desc">Newest first</option>
              <option value="joined-asc">Oldest first</option>
              <option value="orders-desc">Most orders</option>
              <option value="orders-asc">Fewest orders</option>
              <option value="spend-desc">Highest spend</option>
              <option value="spend-asc">Lowest spend</option>
              <option value="reviews-desc">Most reviews</option>
              <option value="rating-desc">Highest rating given</option>
            </select>
            {anyFilter && (<button className="bc-btn bc-tooltip" onClick={()=>{setTypeFilter("All");setAreaFilter("All areas");setRatingFilter("All ratings");setSortBy("joined");setSortDir("desc");setPage(0);}} data-tooltip="Reset all filters"><Icon name="x" size={15}/>Clear</button>)}
          </div>
        </div>
      )}

      {/* ── Result bar ── */}
      <div className="bc-result-bar">
        Showing <b>{filtered.length}</b> customer{filtered.length!==1?"s":""}
        {typeFilter!=="All" && <> · <span className="bc-result-tag">{typeFilter}</span></>}
        {areaFilter!=="All areas" && <> · <span className="bc-result-tag">{areaFilter}</span></>}
        {ratingFilter!=="All ratings" && <> · <span className="bc-result-tag">{ratingFilter}</span></>}
        {query && <> · matching "<b>{query}</b>"</>}
      </div>

      {/* ── Table ── */}
      <div className="bc-card" style={{padding:0,overflow:"hidden"}}>
        <div style={{overflowX:"auto"}}>
          <table className="bc-table bc-table--analytics">
            <thead>
              <tr>
                <th style={{minWidth:180}}>Customer</th>
                <th>Area</th>
                <th className="num bc-th-sort" onClick={()=>toggleSort("orders")}>Orders <SortIcon col="orders"/></th>
                <th className="num bc-th-sort" onClick={()=>toggleSort("spend")}>Total spent <SortIcon col="spend"/></th>
                <th className="num">Avg order</th>
                <th className="num bc-th-sort" onClick={()=>toggleSort("reviews")}>Reviews <SortIcon col="reviews"/></th>
                <th className="num bc-th-sort" onClick={()=>toggleSort("rating")}>Rating given <SortIcon col="rating"/></th>
                <th>Fav chef</th>
                <th>Last order</th>
                <th>Type</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {paged.map(c=>{
                const avgOrder = c.orders>0 ? Math.round(c.spend/c.orders) : 0;
                const cr = custRating(c);
                return (
                  <tr key={c.docId} onClick={()=>setDetail(c)} style={{cursor:"pointer"}}>
                    <td>
                      <div className="bc-recipe-cell">
                        <Avatar name={c.name} kind="cust"/>
                        <div>
                          <div style={{display:"flex",alignItems:"center",gap:8}}>
                            <div className="bc-recipe-name">{c.name}</div>
                            {window.BC_testAccounts && window.BC_testAccounts.isTestCustomer(c.docId) && (
                              <span style={{
                                background:"var(--c-primary)",
                                color:"#fff",
                                fontSize:10,
                                fontWeight:700,
                                padding:"2px 8px",
                                borderRadius:4,
                                whiteSpace:"nowrap"
                              }}>TEST</span>
                            )}
                          </div>
                          {c.email && can("sensitive","viewContactInfo") && <div className="bc-recipe-id">{c.email}</div>}
                        </div>
                      </div>
                    </td>
                    <td className="bc-muted-cell"><span className="bc-area-tag"><Icon name="pin" size={12}/>{c.area}</span></td>
                    <td className="num bc-strong">{c.orders||"—"}</td>
                    <td className="num"><Gate need="sensitive" action="viewFinancials">{c.spend?egp(c.spend):"—"}</Gate></td>
                    <td className="num bc-muted-cell"><Gate need="sensitive" action="viewFinancials">{avgOrder?egp(avgOrder):"—"}</Gate></td>
                    <td className="num bc-muted-cell">{c.reviews||"—"}</td>
                    <td className="num">{cr
                      ? <span className="bc-rating"><Icon name="star" size={12} stroke={0} fill="var(--c-saffron)"/>{cr}</span>
                      : <span className="bc-muted-cell">—</span>}</td>
                    <td className="bc-muted-cell">{c.fav||"—"}</td>
                    <td className="bc-muted-cell" style={{whiteSpace:"nowrap"}}>{c.last}</td>
                    <td>{c.repeat
                      ? <span className="bc-plan bc-plan--repeat">Repeat</span>
                      : <span className="bc-plan bc-plan--new">New</span>}
                    </td>
                    <td><Icon name="eye" size={14} style={{opacity:.4}}/></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
        {filtered.length===0 && <div className="bc-empty">No customers match these filters.</div>}
        {hasMore && (
          <div style={{padding:"14px 20px",borderTop:"1px solid var(--c-line)"}}>
            <button className="bc-btn" style={{width:"100%"}} onClick={()=>setPage(p=>p+1)}>
              Show more ({filtered.length - paged.length} remaining)
            </button>
          </div>
        )}
      </div>

      <Modal open={!!detail} onClose={()=>setDetail(null)} title={detail?.name||""}>
        {detail && <CustomerDetail c={detail} onDelete={()=>setDetail(null)}/>}
      </Modal>
    </div>
  );
}

/* ── Customer Detail ── */
function CustomerDetail({ c, onDelete }) {
  const { can } = usePermissions();
  const showContact = can("sensitive","viewContactInfo");
  const [isTestAccount, setIsTestAccount] = useS(window.BC_testAccounts ? window.BC_testAccounts.isTestCustomer(c.docId) : false);
  const [tab, setTab] = useS("info");
  const theirOrders = useMemo(()=>(window.BC.orders||[]).filter(o=>o.clientId===c.docId).slice(0,10), [c.docId]);

  function toggleTestAccount() {
    if (window.BC_testAccounts) {
      window.BC_testAccounts.toggleCustomer(c.docId);
      setIsTestAccount(!isTestAccount);
    }
  }

  return (
    <div className="bc-detail-modal">
      {/* Header */}
      <div className="bc-detail-header">
        <div className="bc-detail-avatar" style={{background:isTestAccount?"color-mix(in srgb,#C2410C 25%,transparent)":"color-mix(in srgb,var(--c-primary) 20%,transparent)"}}>
          {c.name.charAt(0).toUpperCase()}
        </div>
        <div className="bc-detail-header-info">
          <div className="bc-detail-header-title">{c.name}</div>
          <div className="bc-detail-header-sub">{c.email || "—"}</div>
        </div>
        <div className="bc-detail-header-actions">
          {isTestAccount && <span style={{background:"var(--c-primary)",color:"#fff",fontSize:10,fontWeight:700,padding:"4px 8px",borderRadius:6,whiteSpace:"nowrap"}}>TEST</span>}
        </div>
      </div>

      {/* Stats Band */}
      <div className="bc-detail-stats-band">
        <div className="bc-detail-stat-item">
          <div className="bc-detail-stat-value">{c.orders||0}</div>
          <div className="bc-detail-stat-label">Orders</div>
        </div>
        <div className="bc-detail-stat-item">
          <div className="bc-detail-stat-value">{c.spend?egpK(c.spend):"—"}</div>
          <div className="bc-detail-stat-label">Spent</div>
        </div>
        <div className="bc-detail-stat-item">
          <div className="bc-detail-stat-value">{c.reviews||0}</div>
          <div className="bc-detail-stat-label">Reviews</div>
        </div>
        <div className="bc-detail-stat-item">
          <div className="bc-detail-stat-value">{c.credits||0}</div>
          <div className="bc-detail-stat-label">Credits</div>
        </div>
      </div>

      {/* Tabs */}
      <div className="bc-detail-tabs">
        <button className={"bc-detail-tab"+(tab==="info"?" is-active":"")} onClick={()=>setTab("info")}>Info</button>
        {theirOrders.length > 0 && <button className={"bc-detail-tab"+(tab==="orders"?" is-active":"")} onClick={()=>setTab("orders")}>Orders ({theirOrders.length})</button>}
      </div>

      {/* Body */}
      <div className="bc-detail-body">
        {tab === "info" ? (
          <>
            <div className="bc-detail-info-row">
              <span className="bc-detail-info-label">Customer type</span>
              <span className="bc-detail-info-value">{c.repeat ? "Repeat" : "New"}</span>
            </div>
            <div className="bc-detail-info-row">
              <span className="bc-detail-info-label">Joined</span>
              <span className="bc-detail-info-value">{c.joined||"—"}</span>
            </div>
            <div className="bc-detail-info-row">
              <span className="bc-detail-info-label">Last order</span>
              <span className="bc-detail-info-value">{c.last||"—"}</span>
            </div>
            {c.fav && c.fav!=="—" && (
              <div className="bc-detail-info-row">
                <span className="bc-detail-info-label">Favourite chef</span>
                <span className="bc-detail-info-value">{c.fav}</span>
              </div>
            )}
            <div className="bc-detail-info-row">
              <span className="bc-detail-info-label">Phone</span>
              <span className="bc-detail-info-value">
                {showContact ? (c.phone || "—") : <span className="bc-redacted"><Icon name="key" size={11}/>Hidden</span>}
              </span>
            </div>
            <div className="bc-detail-info-row">
              <span className="bc-detail-info-label">Area</span>
              <span className="bc-detail-info-value">{c.area||"—"}</span>
            </div>
          </>
        ) : (
          <table className="bc-table" style={{marginTop:0}}>
            <thead><tr><th>Order</th><th>Chef</th><th className="num">Value</th><th>Status</th></tr></thead>
            <tbody>
              {theirOrders.map(o=>(
                <tr key={o.docId}>
                  <td className="bc-strong">{o.id}</td>
                  <td className="bc-muted-cell">{o.chef}</td>
                  <td className="num">{egp(o.value)}</td>
                  <td><Pill status={o.status} sm/></td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      {/* Footer */}
      <div className="bc-detail-footer">
        <button className="bc-btn" onClick={toggleTestAccount} style={{flex:1}}>
          {isTestAccount ? "✓ Test Account" : "Mark as test"}
        </button>
        <button className="bc-btn bc-btn--danger" onClick={async()=>{
          if(!window.confirm(`Delete ${c.name}? This cannot be undone.`)) return;
          try {
            await window.BC_actions.deleteCustomer(c.docId);
            onDelete?.();
          } catch(e) {
            alert("Error deleting customer: " + e.message);
          }
        }} style={{flex:1}}>
          <Icon name="trash" size={14}/> Delete
        </button>
      </div>
    </div>
  );
}

/* ══════════════════════════════ DISHES ══════════════════════════════ */
function DishesView({ query }) {
  const { can } = usePermissions();
  const { dishes } = window.BC;
  const [detail,      setDetail]      = useS(null);
  const [chefFilter,  setChefFilter]  = useS("All chefs");
  const [categoryFilter, setCategoryFilter] = useS("All categories");
  const [priceFilter, setPriceFilter] = useS("All prices");
  const [availFilter, setAvailFilter] = useS("All");
  const [ratingFilter, setRatingFilter] = useS("All ratings");
  const [sortBy,      setSortBy]      = useS("newest");
  const [sortDir,     setSortDir]     = useS("desc");
  const [page,        setPage]        = useS(0);
  const [localSearch, setLocalSearch] = useS("");
  const showTestData = useShowTestData();  // global toggle
  const [showFilters, setShowFilters] = useS(false);  // Collapsible filters
  const [, setTick] = useS(0);
  const PER_PAGE = 50;

  // Listen for test account changes
  React.useEffect(() => {
    const handleTestChange = () => setTick(t => t+1);
    window.addEventListener("testAccountsChanged", handleTestChange);
    return () => window.removeEventListener("testAccountsChanged", handleTestChange);
  }, []);

  // Filter test dishes when in "Live" mode — thread logic:
  // a dish is test if it's individually flagged OR its chef is a test chef.
  const all = useMemo(() => {
    let dishList = dishes || [];
    if (!showTestData && window.BC_testAccounts) {
      const t = window.BC_testAccounts;
      dishList = dishList.filter(d => !t.isTestDish(d.docId) && !t.isTestChef(d.chefId));
    }
    return dishList;
  }, [dishes, showTestData]);

  const chefOptions = useMemo(() => {
    const s = new Set(all.map(d=>d.chef).filter(Boolean));
    return ["All chefs", ...Array.from(s).sort()];
  }, [all]);

  const categoryOptions = useMemo(() => {
    const s = new Set(all.map(d=>d.category).filter(Boolean));
    return ["All categories", ...Array.from(s).sort()];
  }, [all]);

  const availOptions = ["All","Available","Out of stock"];
  const priceRanges = ["All prices","Under EGP 50","EGP 50-100","EGP 100-200","Above EGP 200"];

  function matchPrice(d) {
    if (priceFilter==="All prices") return true;
    const p = d.price || 0;
    if (priceFilter==="Under EGP 50") return p < 50;
    if (priceFilter==="EGP 50-100") return p >= 50 && p < 100;
    if (priceFilter==="EGP 100-200") return p >= 100 && p < 200;
    if (priceFilter==="Above EGP 200") return p >= 200;
    return true;
  }

  function matchRating(d) {
    if (ratingFilter==="All ratings") return true;
    const r = d.rating || 0;
    if (ratingFilter==="5 ★") return r === 5;
    if (ratingFilter==="4+ ★") return r >= 4;
    if (ratingFilter==="3+ ★") return r >= 3;
    if (ratingFilter==="Below 3 ★") return r && r < 3;
    return true;
  }

  function sortVal(d) {
    if (sortBy==="newest") return tsMs(d.createdAt);
    if (sortBy==="price")  return d.price || 0;
    if (sortBy==="rating") return d.rating || 0;
    if (sortBy==="orders") return d.orders || 0;
    return tsMs(d.createdAt);
  }

  const filtered = useMemo(()=>
    all.filter(d =>
      (chefFilter==="All chefs" || d.chef===chefFilter) &&
      (categoryFilter==="All categories" || d.category===categoryFilter) &&
      (availFilter==="All" || (availFilter==="Available" ? d.available : !d.available)) &&
      matchPrice(d) &&
      matchRating(d) &&
      (!query || (d.name+d.chef+d.category+(d.description||"")).toLowerCase().includes(query.toLowerCase())) &&
      (!localSearch || (d.name+d.chef+d.category).toLowerCase().includes(localSearch.toLowerCase()))
    ).sort((a,b)=> sortDir==="desc" ? sortVal(b)-sortVal(a) : sortVal(a)-sortVal(b)),
    [all, chefFilter, categoryFilter, availFilter, priceFilter, ratingFilter, query, sortBy, sortDir, localSearch]
  );

  const paged = filtered.slice(0,(page+1)*PER_PAGE);
  const hasMore = filtered.length > paged.length;
  const anyFilter = chefFilter!=="All chefs" || categoryFilter!=="All categories" || priceFilter!=="All prices" || availFilter!=="All" || ratingFilter!=="All ratings" || sortBy!=="newest" || sortDir!=="desc";

  // Stats
  const totalDishes = all.length;
  const availCount = all.filter(d=>d.available).length;
  const avgPrice = all.length ? Math.round(all.reduce((s,d)=>s+(d.price||0),0)/all.length) : 0;
  const totalOrders = all.reduce((s,d)=>s+(d.orders||0),0);

  function toggleSort(col){
    if (sortBy===col) setSortDir(d=>d==="desc"?"asc":"desc");
    else { setSortBy(col); setSortDir("desc"); }
    setPage(0);
  }
  function SortIcon({col}){
    if (sortBy!==col) return <span style={{opacity:.3,fontSize:10}}>⇅</span>;
    return <span style={{color:"var(--c-primary-text)",fontSize:10}}>{sortDir==="desc"?"↓":"↑"}</span>;
  }

  function exportCSV(){
    const cols=["Dish","Chef","Category","Price (EGP)","Rating","Orders","Available","Added"];
    const rows=filtered.map(d=>[d.name,d.chef,d.category,d.price||"",d.rating||"",d.orders||0,d.available?"Yes":"No",d.added||""]);
    const csv=[cols.join(","),...rows.map(r=>r.map(v=>`"${String(v).replace(/"/g,'""')}"`).join(","))].join("\n");
    const blob=new Blob(["﻿"+csv],{type:"text/csv;charset=utf-8"});
    const url=URL.createObjectURL(blob);
    const a=document.createElement("a");
    a.href=url; a.download=`betychef-dishes-${new Date().toISOString().slice(0,10)}.csv`; a.click();
    URL.revokeObjectURL(url);
  }

  return (
    <div className="bc-stack">
      {/* Search */}
      <input className="bc-input" type="text" placeholder="🔍 Search dishes by name, chef, category..."
        value={localSearch} onChange={e=>{setLocalSearch(e.target.value);setPage(0);}} style={{padding:"10px 14px",fontSize:"14px"}}/>

      {/* Stats */}
      <div className="bc-chef-stats-grid">
        <div className="bc-chef-stat-card" onClick={()=>{setChefFilter("All chefs");setCategoryFilter("All categories");setPriceFilter("All prices");setAvailFilter("All");setRatingFilter("All ratings");setSortBy("newest");setSortDir("desc");setPage(0);}} style={{cursor:"pointer"}}>
          <div className="bc-cstat-num">{totalDishes.toLocaleString()}</div>
          <div className="bc-cstat-label">Total dishes</div>
          <div className="bc-cstat-sub">on the platform</div>
        </div>
        <div className="bc-chef-stat-card">
          <div className="bc-cstat-dot" style={{background:"var(--c-green)"}}/>
          <div className="bc-cstat-num" style={{color:"var(--c-green)"}}>{availCount}</div>
          <div className="bc-cstat-label">Available now</div>
          <div className="bc-cstat-sub">{totalDishes ? Math.round(availCount/totalDishes*100) : 0}% in stock</div>
        </div>
        <div className="bc-chef-stat-card">
          <div className="bc-cstat-num">{egp(avgPrice)}</div>
          <div className="bc-cstat-label">Avg. price</div>
          <div className="bc-cstat-sub">across all dishes</div>
        </div>
        <div className="bc-chef-stat-card">
          <div className="bc-cstat-num">{totalOrders.toLocaleString()}</div>
          <div className="bc-cstat-label">Total orders</div>
          <div className="bc-cstat-sub">all dishes combined</div>
        </div>
      </div>

      {/* Filter toggle + actions */}
      <div className="bc-toolbar">
        <div className="bc-toolbar-right" style={{gap:8}}>
          <button className="bc-btn bc-tooltip" onClick={()=>setShowFilters(!showFilters)} data-tooltip={showFilters?"Hide filters":"Show filters"} style={{background:"var(--c-surface-2)",fontWeight:600,padding:"10px 14px"}}>
            <Icon name={showFilters?"chevron-up":"sliders"} size={16}/>Filters
          </button>
          {can("analytics","export") && <button className="bc-btn" onClick={exportCSV}><Icon name="download" size={16}/>Export</button>}
        </div>
      </div>

      {/* ── Collapsible filters panel ── */}
      {showFilters && (
        <div className="bc-toolbar" style={{paddingTop:0}}>
          <div style={{display:"flex",gap:12,flexWrap:"wrap",width:"100%"}}>
            <select className="bc-select" value={chefFilter} onChange={e=>{setChefFilter(e.target.value);setPage(0);}}>
              {chefOptions.map(c=><option key={c}>{c}</option>)}
            </select>
            <select className="bc-select" value={categoryFilter} onChange={e=>{setCategoryFilter(e.target.value);setPage(0);}}>
              {categoryOptions.map(c=><option key={c}>{c}</option>)}
            </select>
            <select className="bc-select" value={priceFilter} onChange={e=>{setPriceFilter(e.target.value);setPage(0);}}>
              {priceRanges.map(p=><option key={p}>{p}</option>)}
            </select>
            <select className="bc-select" value={availFilter} onChange={e=>{setAvailFilter(e.target.value);setPage(0);}}>
              {availOptions.map(a=><option key={a}>{a}</option>)}
            </select>
            <select className="bc-select" value={ratingFilter} onChange={e=>{setRatingFilter(e.target.value);setPage(0);}}>
              {["All ratings","5 ★","4+ ★","3+ ★","Below 3 ★"].map(r=><option key={r}>{r}</option>)}
            </select>
            {anyFilter && (<button className="bc-btn" onClick={()=>{setChefFilter("All chefs");setCategoryFilter("All categories");setPriceFilter("All prices");setAvailFilter("All");setRatingFilter("All ratings");setSortBy("newest");setSortDir("desc");setPage(0);}}><Icon name="x" size={15}/>Clear</button>)}
          </div>
        </div>
      )}

      {/* Results */}
      <div className="bc-result-bar">
        Showing <b>{filtered.length}</b> dish{filtered.length!==1?"es":""} {chefFilter!=="All chefs" && <> · <span className="bc-result-tag">{chefFilter}</span></>} {categoryFilter!=="All categories" && <> · <span className="bc-result-tag">{categoryFilter}</span></>} {priceFilter!=="All prices" && <> · <span className="bc-result-tag">{priceFilter}</span></>} {query && <> · matching "<b>{query}</b>"</>}
      </div>

      {/* Table */}
      <div className="bc-card" style={{padding:0,overflow:"hidden"}}>
        <div style={{overflowX:"auto"}}>
          <table className="bc-table bc-table--analytics">
            <thead><tr>
              <th style={{minWidth:200}}>Dish</th><th>Chef</th><th>Category</th><th className="num bc-th-sort" onClick={()=>toggleSort("price")}>Price <SortIcon col="price"/></th>
              <th className="num">Rating</th><th className="num bc-th-sort" onClick={()=>toggleSort("orders")}>Orders <SortIcon col="orders"/></th><th>Available</th><th>Added</th><th></th>
            </tr></thead>
            <tbody>
              {paged.map(d=>(
                <tr key={d.docId} onClick={()=>setDetail(d)} style={{cursor:"pointer"}}>
                  <td>
                    <div style={{display:"flex",alignItems:"center",gap:8}}>
                      <span className="bc-strong">{d.name}</span>
                      {window.BC_testAccounts && window.BC_testAccounts.isTestDish(d.docId) && (<span style={{background:"var(--c-primary)",color:"#fff",fontSize:10,fontWeight:700,padding:"2px 8px",borderRadius:4,whiteSpace:"nowrap"}}>TEST</span>)}
                    </div>
                  </td>
                  <td className="bc-muted-cell">{d.chef||"—"}</td>
                  <td className="bc-muted-cell">{d.category||"—"}</td>
                  <td className="num bc-strong">{d.price ? egp(d.price) : "—"}</td>
                  <td className="num">{d.rating ? <><Icon name="star" size={12} stroke={0} fill="var(--c-saffron)"/>{d.rating}</> : "—"}</td>
                  <td className="num">{d.orders || "—"}</td>
                  <td>{d.available ? <span style={{color:"var(--c-green)",fontWeight:600}}>✓ Yes</span> : <span style={{color:"#999",fontWeight:600}}>Out</span>}</td>
                  <td className="bc-muted-cell" style={{whiteSpace:"nowrap"}}>{d.added||"—"}</td>
                  <td><Icon name="chevron" size={16} style={{opacity:.4}}/></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        {filtered.length===0 && <div className="bc-empty">No dishes match these filters.</div>}
        {hasMore && (<div style={{padding:"14px 20px",borderTop:"1px solid var(--c-line)"}}><button className="bc-btn" style={{width:"100%"}} onClick={()=>setPage(p=>p+1)}>Show more ({filtered.length - paged.length} remaining)</button></div>)}
      </div>

      <Modal open={!!detail} onClose={()=>setDetail(null)} title={detail?.name||""} wide>
        {detail && <DishDetail d={detail}/>}
      </Modal>
    </div>
  );
}

/* ── Dish Detail ── */
function DishDetail({ d }) {
  const [isTestAccount, setIsTestAccount] = useS(window.BC_testAccounts ? window.BC_testAccounts.isTestDish(d.docId) : false);

  function toggleTestAccount() {
    if (window.BC_testAccounts) {
      window.BC_testAccounts.toggleDish(d.docId);
      setIsTestAccount(!isTestAccount);
    }
  }

  return (
    <div className="bc-detail-modal">
      {/* Header */}
      <div className="bc-detail-header">
        <div className="bc-detail-avatar" style={{background:"color-mix(in srgb,var(--c-green) 20%,transparent)"}}>
          🍽
        </div>
        <div className="bc-detail-header-info">
          <div className="bc-detail-header-title">{d.name}</div>
          <div className="bc-detail-header-sub">{d.chef || "—"}</div>
        </div>
        <div className="bc-detail-header-actions">
          {isTestAccount && <span style={{background:"var(--c-primary)",color:"#fff",fontSize:10,fontWeight:700,padding:"4px 8px",borderRadius:6,whiteSpace:"nowrap"}}>TEST</span>}
        </div>
      </div>

      {/* Stats Band */}
      <div className="bc-detail-stats-band">
        <div className="bc-detail-stat-item">
          <div className="bc-detail-stat-value">{d.price ? egp(d.price) : "—"}</div>
          <div className="bc-detail-stat-label">Price</div>
        </div>
        <div className="bc-detail-stat-item">
          <div className="bc-detail-stat-value">{d.category||"—"}</div>
          <div className="bc-detail-stat-label">Category</div>
        </div>
        <div className="bc-detail-stat-item">
          <div className="bc-detail-stat-value">{d.orders || 0}</div>
          <div className="bc-detail-stat-label">Orders</div>
        </div>
        <div className="bc-detail-stat-item">
          <div className="bc-detail-stat-value">{d.rating ? <>{d.rating} <Icon name="star" size={12} stroke={0} fill="var(--c-saffron)" style={{verticalAlign:"middle"}}/></> : "—"}</div>
          <div className="bc-detail-stat-label">Rating</div>
        </div>
      </div>

      {/* Body */}
      <div className="bc-detail-body">
        <div className="bc-detail-info-row">
          <span className="bc-detail-info-label">Status</span>
          <span className="bc-detail-info-value" style={{color:d.available?"var(--c-green)":"#999"}}>{d.available ? "✓ Available" : "Out of stock"}</span>
        </div>
        <div className="bc-detail-info-row">
          <span className="bc-detail-info-label">Added</span>
          <span className="bc-detail-info-value">{d.added||"—"}</span>
        </div>
        {d.description && (
          <div className="bc-detail-info-row">
            <span className="bc-detail-info-label">Description</span>
            <span className="bc-detail-info-value">{d.description}</span>
          </div>
        )}
      </div>

      {/* Footer */}
      <div className="bc-detail-footer">
        <button className="bc-btn" onClick={toggleTestAccount} style={{flex:1}}>
          {isTestAccount ? "✓ Test Dish" : "Mark as test"}
        </button>
      </div>
    </div>
  );
}

/* ══════════════════════════════ SETTINGS & TEAM ══════════════════════════════ */
function SettingsView({ navigate }) {
  const [tab, setTab] = useS("team");
  const [teamData, setTeamData] = useS(null);
  const [addOpen, setAddOpen] = useS(false);
  const [editMember, setEditMember] = useS(null);
  const [newFirst,  setNewFirst]  = useS("");
  const [newMiddle, setNewMiddle] = useS("");
  const [newLast,   setNewLast]   = useS("");
  const [newRole, setNewRole] = useS("viewer");
  const [inviting, setInviting] = useS(false);
  const [invited,  setInvited]  = useS(null);  // {companyEmail, password, emailSent} — shown after a successful invite
  const [msg, setMsg] = useS("");
  const [permissionsOpen, setPermissionsOpen] = useS(null);
  const [memberPermissions, setMemberPermissions] = useS({});
  const [, setTick] = useS(0);

  React.useEffect(() => {
    const onChange = () => {
      if (window.BC_teamAccess) setTeamData(window.BC_teamAccess.getTeamData());
      setTick(t => t+1);
    };
    onChange();
    window.addEventListener("teamAccessChanged", onChange);
    return () => window.removeEventListener("teamAccessChanged", onChange);
  }, []);

  // Creates the real login (firstname.lastname@betychef.com + a generated
  // password) directly via Firebase Auth — no email is sent; the credentials
  // are shown once on screen and you share them manually. The account is
  // already real and working, so the member is recorded as "active" right away.
  async function handleAddMember() {
    if (!newFirst.trim() || !newLast.trim()) return setMsg("First and last name are required");
    setInviting(true);
    setMsg("");
    try {
      const { email, password, fullName } = await window.BC_actions.createTeamMemberAccount({
        firstName: newFirst.trim(), middleName: newMiddle.trim(), lastName: newLast.trim(), role: newRole,
      });
      window.BC_teamAccess.addMember(fullName, email, newRole, { status: "active" });
      setInvited({ companyEmail: email, password });
      setNewFirst(""); setNewMiddle(""); setNewLast(""); setNewRole("viewer");
    } catch (e) {
      setMsg(e.message || "Couldn't create the account");
    }
    setInviting(false);
  }

  function handleRemove(id) {
    if (window.confirm("Remove this team member?")) {
      if (window.BC_teamAccess) {
        window.BC_teamAccess.removeMember(id);
        setMsg("✓ Member removed");
      }
    }
  }

  function handleActivate(id) {
    if (window.BC_teamAccess) {
      window.BC_teamAccess.activateMember(id);
      setMsg("✓ Member activated");
    }
  }

  // Open the editor with a DEEP COPY of this member's real, current
  // permissions — editing the draft never touches the stored copy (or any
  // other member sharing the same role template) until Save is pressed.
  function openPermissions(member) {
    setMemberPermissions(JSON.parse(JSON.stringify(member.permissions || {})));
    setPermissionsOpen(member.id);
  }
  function togglePerm(section, action) {
    setMemberPermissions(p => ({
      ...p,
      [section]: { ...p[section], [action]: !p[section]?.[action] },
    }));
  }
  function savePermissions() {
    if (window.BC_teamAccess && permissionsOpen) {
      window.BC_teamAccess.updateMemberPermissions(permissionsOpen, memberPermissions);
      setMsg("✓ Permissions updated");
    }
    setPermissionsOpen(null);
  }

  if (!teamData) return <div className="bc-stack" style={{padding:20}}>Loading...</div>;

  const activity = window.BC_teamAccess ? window.BC_teamAccess.getActivity() : [];

  return (
    <div className="bc-stack">
      {/* Tabs */}
      <div style={{display:"flex",gap:0,borderBottom:"1px solid var(--c-line)"}}>
        <button onClick={()=>setTab("team")} style={{padding:"12px 20px",borderBottom:tab==="team"?"2px solid var(--c-primary)":"none",color:tab==="team"?"var(--c-ink)":"var(--c-ink-2)",background:"none",border:"none",cursor:"pointer",fontWeight:600}}>👥 Team Acces</button>
        <button onClick={()=>setTab("activity")} style={{padding:"12px 20px",borderBottom:tab==="activity"?"2px solid var(--c-primary)":"none",color:tab==="activity"?"var(--c-ink)":"var(--c-ink-2)",background:"none",border:"none",cursor:"pointer",fontWeight:600}}>📋 Activity Log</button>
      </div>

      {msg && <div style={{padding:"12px 16px",background:"var(--c-surface-2)",borderRadius:8,color:"var(--c-primary-text)",marginBottom:16}}>{msg}</div>}

      {/* Team Members Tab */}
      {tab === "team" && (
        <div>
          <div style={{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:20}}>
            <h2 style={{margin:0,fontSize:20,fontWeight:700}}>Team Acces</h2>
            <button className="bc-btn bc-btn--primary" onClick={()=>{setInvited(null); setAddOpen(true);}}><Icon name="plus" size={16}/>Add member</button>
          </div>

          {/* Team screen access — see exactly what a member sees, on every
              screen, without a second login. Picking someone here pops this
              bar out to float with you; closing it brings you right back. */}
          {teamData.members.some(m=>m.status==="active") && (
            <div className="bc-teamaccess-bar">
              <span className="bc-teamaccess-bar-label"><Icon name="eye" size={15}/>Team screen access</span>
              <select className="bc-teamaccess-bar-select" value=""
                onChange={e=>{ const id=e.target.value; if(!id) return; window.BC_teamAccess.setPreviewMember(id); navigate && navigate("overview"); }}>
                <option value="">View as…</option>
                {teamData.members.filter(m=>m.status==="active").map(m=>(
                  <option key={m.id} value={m.id}>{m.name} · {m.role.replace("_"," ")}</option>
                ))}
              </select>
            </div>
          )}

          {/* Founder */}
          <div className="bc-card" style={{marginBottom:12}}>
            <div style={{display:"grid",gridTemplateColumns:"1fr auto auto auto",alignItems:"center",gap:16}}>
              <div>
                <div style={{fontWeight:700}}>{teamData.founder.name}</div>
                <div style={{fontSize:12,color:"var(--c-ink-2)"}}>{teamData.founder.email}</div>
              </div>
              <div style={{fontSize:12,background:"var(--c-primary)",color:"#fff",padding:"4px 12px",borderRadius:6,fontWeight:700}}>FOUNDER</div>
              <div style={{fontSize:12,color:"var(--c-green)",fontWeight:600}}>● Active</div>
              <div style={{fontSize:11,color:"var(--c-ink-2)"}}>Full access</div>
            </div>
          </div>

          {/* Team Members */}
          {teamData.members.length === 0 ? (
            <div style={{padding:40,textAlign:"center",color:"var(--c-ink-2)"}}>No team members yet. Add your first team member to get started!</div>
          ) : (
            teamData.members.map(member => (
              <div key={member.id} className="bc-card" style={{marginBottom:12}}>
                <div style={{display:"grid",gridTemplateColumns:"1fr auto auto auto auto",alignItems:"center",gap:12}}>
                  <div>
                    <div style={{fontWeight:700}}>{member.name}</div>
                    <div style={{fontSize:12,color:"var(--c-ink-2)"}}>{member.email}{member.personalEmail && <> · sent to {member.personalEmail}</>}</div>
                  </div>
                  <div style={{fontSize:11,textTransform:"uppercase",background:"var(--c-surface-2)",padding:"4px 10px",borderRadius:6,fontWeight:700}}>{member.role}</div>
                  <div style={{fontSize:12,color:member.status==="active"?"var(--c-green)":"var(--c-saffron)",fontWeight:600}}>● {member.status==="active"?"Active":"Pending"}</div>
                  {member.status === "pending" && (
                    <button className="bc-btn" style={{fontSize:11,padding:"4px 10px"}} onClick={()=>handleActivate(member.id)}>Activate</button>
                  )}
                  {member.status === "active" && (
                    <button className="bc-btn" style={{fontSize:11,padding:"4px 10px"}} onClick={()=>openPermissions(member)}>Permissions</button>
                  )}
                  <button className="bc-btn" style={{fontSize:11,padding:"4px 10px",color:"#d32f2f"}} onClick={()=>handleRemove(member.id)}>Remove</button>
                </div>
              </div>
            ))
          )}
        </div>
      )}


      {/* Activity Log Tab */}
      {tab === "activity" && (
        <div>
          <h2 style={{fontSize:20,fontWeight:700,marginBottom:20}}>Activity Log</h2>
          {activity.length === 0 ? (
            <div style={{padding:40,textAlign:"center",color:"var(--c-ink-2)"}}>No activity yet</div>
          ) : (
            <div>
              {activity.slice(0,50).map((log, i) => (
                <div key={i} style={{padding:12,borderBottom:"1px solid var(--c-line)",display:"grid",gridTemplateColumns:"120px 1fr auto",gap:16,alignItems:"center"}}>
                  <div style={{fontSize:11,color:"var(--c-ink-2)"}}>
                    {new Date(log.timestamp).toLocaleTimeString()}
                  </div>
                  <div>
                    <div style={{fontWeight:600,fontSize:13}}>{log.description}</div>
                    <div style={{fontSize:11,color:"var(--c-ink-2)"}}>{log.action.replace(/_/g, " ")}</div>
                  </div>
                  <div style={{fontSize:11,color:"var(--c-ink-2)"}}>
                    {new Date(log.timestamp).toLocaleDateString()}
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {/* Add Member Modal */}
      <Modal open={addOpen} onClose={()=>setAddOpen(false)} title={invited ? "Account created" : "Add Team Member"} wide>
        <div style={{padding:20}}>
          {invited ? (
            // ── Credentials screen — shown once, right after the account is created.
            // Nothing is emailed; you copy/share these with the person yourself. ──
            <div>
              <div style={{display:"flex",alignItems:"center",gap:10,marginBottom:16}}>
                <span style={{width:36,height:36,borderRadius:"50%",background:"color-mix(in srgb,var(--c-green) 16%,transparent)",display:"grid",placeItems:"center"}}>
                  <Icon name="check" size={18} style={{color:"var(--c-green)"}}/>
                </span>
                <div>
                  <div style={{fontWeight:700,fontSize:15}}>{invited.fullName ? `${invited.fullName}'s account is live` : "Account is live"}</div>
                  <div style={{fontSize:12,color:"var(--c-ink-2)"}}>Share these credentials with them yourself — nothing was emailed</div>
                </div>
              </div>
              <div style={{background:"var(--c-surface-2)",borderRadius:10,padding:14,fontSize:13,fontFamily:"var(--font-mono)"}}>
                <div style={{marginBottom:8}}><span style={{color:"var(--c-ink-2)"}}>Login email — </span><b>{invited.companyEmail}</b></div>
                <div><span style={{color:"var(--c-ink-2)"}}>Temporary password — </span><b>{invited.password}</b></div>
              </div>
              <button className="bc-btn" style={{width:"100%",marginTop:10}}
                onClick={()=>{
                  navigator.clipboard.writeText(`Login: ${invited.companyEmail}\nPassword: ${invited.password}`);
                  setMsg("✓ Copied to clipboard");
                }}>
                <Icon name="download" size={14}/>Copy login + password
              </button>
              <p style={{fontSize:12,color:"var(--c-ink-2)",marginTop:12,lineHeight:1.5}}>
                This login only works on this dashboard — no real inbox needed for it. They can change the password from the profile menu after signing in.
              </p>
              <button className="bc-btn bc-btn--primary" style={{width:"100%",marginTop:8}} onClick={()=>{setInvited(null); setAddOpen(false); setMsg("");}}>Done</button>
            </div>
          ) : (
            // ── Add member form ──
            <div>
              <div style={{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:12,marginBottom:16}}>
                <div>
                  <label style={{fontSize:12,fontWeight:700,color:"var(--c-ink-2)",display:"block",marginBottom:4}}>First name *</label>
                  <input className="bc-input" type="text" value={newFirst} onChange={e=>setNewFirst(e.target.value)} placeholder="Nour" autoFocus/>
                </div>
                <div>
                  <label style={{fontSize:12,fontWeight:700,color:"var(--c-ink-2)",display:"block",marginBottom:4}}>Middle name</label>
                  <input className="bc-input" type="text" value={newMiddle} onChange={e=>setNewMiddle(e.target.value)} placeholder="optional"/>
                </div>
                <div>
                  <label style={{fontSize:12,fontWeight:700,color:"var(--c-ink-2)",display:"block",marginBottom:4}}>Last name *</label>
                  <input className="bc-input" type="text" value={newLast} onChange={e=>setNewLast(e.target.value)} placeholder="Hassan"/>
                </div>
              </div>
              <div style={{marginBottom:8}}>
                <label style={{fontSize:12,fontWeight:700,color:"var(--c-ink-2)",display:"block",marginBottom:4}}>Role</label>
                <select className="bc-select" value={newRole} onChange={e=>setNewRole(e.target.value)}>
                  <option value="viewer">Viewer (Read-only)</option>
                  <option value="regular_employee">Regular Employee</option>
                  <option value="manager">Manager</option>
                  <option value="admin">Admin</option>
                </select>
              </div>
              <p style={{fontSize:11.5,color:"var(--c-ink-2)",marginBottom:16,lineHeight:1.5}}>
                Creates their real dashboard login as <b>firstname.lastname@betychef.com</b> with a generated password — shown to you on the next screen to share manually.
              </p>
              {msg && <div className="bc-login-err" style={{marginBottom:12}}>{msg}</div>}
              <div style={{display:"flex",gap:12}}>
                <button className="bc-btn bc-btn--primary" onClick={handleAddMember} disabled={inviting} style={{flex:1}}>
                  {inviting ? "Creating…" : "Create account"}
                </button>
                <button className="bc-btn" onClick={()=>setAddOpen(false)} disabled={inviting} style={{flex:1}}>Cancel</button>
              </div>
            </div>
          )}
        </div>
      </Modal>

      {/* Permissions Modal — every checkbox here is real: it reads and
          writes window.BC_teamAccess via updateMemberPermissions, and every
          screen in the dashboard checks can() against this same data. */}
      <Modal open={!!permissionsOpen} onClose={()=>setPermissionsOpen(null)} title={`Edit Permissions - ${teamData?.members.find(m=>m.id===permissionsOpen)?.name||""}`} wide>
        <div style={{padding:20}}>

          {/* Screens — what shows up in their nav at all */}
          <div className="bc-perm-section">
            <div className="bc-perm-section-title">🧭 Screens</div>
            <div className="bc-perm-section-desc">Which sections appear in their nav bar. Switch one off and it's gone — not greyed out, not blocked, just not there.</div>
            <div style={{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:10}}>
              {[
                {k:"overview",l:"Home"},{k:"orders",l:"Orders"},{k:"chefs",l:"Chef network"},
                {k:"applications",l:"Applications"},{k:"dishes",l:"Dishes"},{k:"customers",l:"Customers"},
                {k:"ops",l:"Operations"},{k:"crm",l:"Outreach"},{k:"notify",l:"Notifications"},
              ].map(item=>(
                <label key={item.k} className="bc-perm-group" style={{display:"flex",alignItems:"center",gap:9,cursor:"pointer",fontSize:13}}>
                  <input type="checkbox" style={{cursor:"pointer",width:17,height:17}}
                    checked={memberPermissions.screens?.[item.k] !== false}
                    onChange={()=>togglePerm("screens",item.k)}/>
                  <span>{item.l}</span>
                </label>
              ))}
            </div>
          </div>

          {/* Section permissions */}
          <div className="bc-perm-section">
            <div className="bc-perm-section-title">📋 Section Permissions</div>
            <div className="bc-perm-section-desc">What actions they can perform in each section.</div>
            <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:24}}>
              {[
                {key:"chefs",section:"Chefs",items:[{k:"view",l:"View"},{k:"delete",l:"Delete"},{k:"pause",l:"Pause"},{k:"approve",l:"Approve"}]},
                {key:"dishes",section:"Dishes",items:[{k:"view",l:"View"}]},
                {key:"orders",section:"Orders",items:[{k:"view",l:"View"}]},
                {key:"customers",section:"Customers",items:[{k:"view",l:"View"}]},
                {key:"outreach",section:"Outreach",items:[{k:"view",l:"View"},{k:"export",l:"Export"},{k:"addToProspect",l:"Add to prospect"}]},
                {key:"notifications",section:"Notifications",items:[{k:"view",l:"View"},{k:"send",l:"Send"}]},
                {key:"analytics",section:"Analytics",items:[{k:"view",l:"View"},{k:"export",l:"Export"}]},
              ].map((group)=>(
                <div key={group.key}>
                  <div style={{fontSize:13,fontWeight:700,marginBottom:12,color:"var(--c-ink)"}}>{group.section}</div>
                  {group.items.map((item)=>(
                    <label key={item.k} style={{display:"flex",alignItems:"center",gap:10,marginBottom:10,cursor:"pointer",fontSize:13}}>
                      <input type="checkbox" style={{cursor:"pointer",width:18,height:18}}
                        checked={!!memberPermissions[group.key]?.[item.k]}
                        onChange={()=>togglePerm(group.key,item.k)}/>
                      <span>{item.l}</span>
                    </label>
                  ))}
                </div>
              ))}
            </div>
          </div>

          {/* Data visibility */}
          <div className="bc-perm-section">
            <div className="bc-perm-section-title">👁️ Data Visibility</div>
            <div className="bc-perm-section-desc">What sensitive numbers they see inside the screens above — hidden fields show as <span className="bc-redacted" style={{verticalAlign:"middle"}}><Icon name="key" size={10}/>•••</span> instead.</div>
            <div style={{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:16}}>
              {[
                {k:"viewFinancials",l:"Commission & revenue",d:"GMV, platform fees, settlement figures"},
                {k:"viewPayouts",l:"Chef payouts",d:"Chef earnings, InstaPay/wallet details"},
                {k:"viewContactInfo",l:"Contact info",d:"Phone, email, delivery address"},
              ].map(item=>(
                <label key={item.k} style={{display:"flex",alignItems:"flex-start",gap:10,cursor:"pointer",padding:12,borderRadius:10,background:"var(--c-surface-2)"}}>
                  <input type="checkbox" style={{cursor:"pointer",width:18,height:18,marginTop:1}}
                    checked={!!memberPermissions.sensitive?.[item.k]}
                    onChange={()=>togglePerm("sensitive",item.k)}/>
                  <span>
                    <div style={{fontWeight:600,fontSize:13}}>{item.l}</div>
                    <div style={{fontSize:11,color:"var(--c-ink-2)",marginTop:2}}>{item.d}</div>
                  </span>
                </label>
              ))}
            </div>
          </div>

          <div style={{display:"flex",gap:12,marginTop:24}}>
            <button className="bc-btn bc-btn--primary" onClick={savePermissions} style={{flex:1}}>Save Permissions</button>
            <button className="bc-btn" onClick={()=>setPermissionsOpen(null)} style={{flex:1}}>Cancel</button>
          </div>
        </div>
      </Modal>
    </div>
  );
}

/* ══════════════════════════════ OPERATIONS ══════════════════════════════ */
/* ── Donut chart component ── */
function DonutChart({ slices, cx=100, cy=100, r=72 }) {
  const C = 2 * Math.PI * r;
  let offset = 0;
  const arcs = slices.map(s => {
    const dash = (s.pct / 100) * C;
    const arc  = { ...s, dash, offset };
    offset += dash;
    return arc;
  });
  const total = slices.reduce((s,x)=>s+x.value,0);
  return (
    <svg viewBox="0 0 200 200" width="200" height="200" style={{flexShrink:0}}>
      {/* Track */}
      <circle cx={cx} cy={cy} r={r} fill="none" stroke="var(--c-surface-2)" strokeWidth="22"/>
      {/* Slices */}
      {arcs.filter(a=>a.dash>0).map((a,i)=>(
        <circle key={i} cx={cx} cy={cy} r={r} fill="none"
          stroke={a.color} strokeWidth="22" strokeLinecap="butt"
          strokeDasharray={`${a.dash.toFixed(2)} ${C}`}
          strokeDashoffset={-a.offset + C/4}
          style={{transition:"stroke-dasharray .5s"}}/>
      ))}
      {/* Center text */}
      <text x={cx} y={cy-8} textAnchor="middle"
        style={{fontFamily:"var(--font-mono)",fontWeight:700,fontSize:15,fill:"var(--c-ink)"}}>
        {egpK(total)}
      </text>
      <text x={cx} y={cy+10} textAnchor="middle"
        style={{fontSize:9,fill:"var(--c-ink-2)"}}>total collected</text>
    </svg>
  );
}

function OpsView() {
  const { ops, orders } = window.BC;
  const showTestData = useShowTestData();  // global toggle
  const [payPeriod, setPayPeriod] = useS("all");   // today | week | month | all

  // Hide orphans always; hide test threads unless TEST mode is on
  const allOrders = useMemo(() => {
    const list = orders || [];
    if (!window.BC_testAccounts) return list;
    return list.filter(o => window.BC_testAccounts.isOrderVisible(o, showTestData));
  }, [orders, showTestData]);
  const td = ts => ts ? (ts.toDate?ts.toDate():new Date(ts)) : null;

  // Period filter
  const periodOrders = useMemo(() => {
    const now = new Date();
    const cutoffs = {
      today: (() => { const d=new Date(now); d.setHours(0,0,0,0); return d; })(),
      week:  (() => { const d=new Date(now); d.setDate(d.getDate()-6); d.setHours(0,0,0,0); return d; })(),
      month: (() => { const d=new Date(now); d.setDate(1); d.setHours(0,0,0,0); return d; })(),
      all:   null,
    };
    const cutoff = cutoffs[payPeriod];
    return allOrders.filter(o => {
      if (!o.paid) return false;
      if (!cutoff) return true;
      const d = td(o.createdAt); return d && d >= cutoff;
    });
  }, [orders, payPeriod]);

  // Channel config — always show all 3 even if zero
  const CHANNELS = [
    { key:"paymob",   label:"Paymob",           color:"#06D001" },
    { key:"instapay", label:"InstaPay",          color:"#9BEC00" },
    { key:"cash",     label:"Cash on Delivery",  color:"#67726B" },
  ];

  const methods = useMemo(() => {
    const groups = {};
    periodOrders.forEach(o => {
      const m = (o.paymentMethod||"paymob").toLowerCase().replace(/[\s_]/g,"");
      const key = m.includes("instapay")?"instapay":m.includes("cash")?"cash":"paymob";
      if (!groups[key]) groups[key] = { tx:0, value:0 };
      groups[key].tx++;
      groups[key].value += o.value;
    });
    const total = periodOrders.length || 1;
    return CHANNELS.map(ch => ({
      ...ch,
      tx:    groups[ch.key]?.tx    || 0,
      value: groups[ch.key]?.value || 0,
      pct:   groups[ch.key] ? Math.round(groups[ch.key].tx / total * 100) : 0,
    }));
  }, [periodOrders]);

  // Money split
  const totalCollected  = periodOrders.reduce((s,o)=>s+o.value,0);
  const betychefCut     = periodOrders.reduce((s,o)=>s+o.fee,0);
  const chefsCut        = totalCollected - betychefCut;

  // Delivery stats from order statuses
  const delivered = allOrders.filter(o=>o.status==="Delivered").length;
  const inTransit = allOrders.filter(o=>["New","Preparing","Ready","On the way"].includes(o.status)).length;
  const cancelled = allOrders.filter(o=>o.status==="Cancelled").length;
  const deliveryRate = allOrders.length ? Math.round(delivered/allOrders.length*100) : 0;

  const PERIODS = [
    { value:"today", label:"Today"      },
    { value:"week",  label:"This week"  },
    { value:"month", label:"This month" },
    { value:"all",   label:"All time"   },
  ];

  return (
    <div className="bc-stack">

      {/* ── SECTION 1: PAYMENTS ── */}
      <div className="bc-ops-section-label">
        <Icon name="card" size={16}/> Payments
      </div>

      {/* Period filter */}
      <div className="bc-segmented" style={{alignSelf:"flex-start"}}>
        {PERIODS.map(p=>(
          <button key={p.value} className={payPeriod===p.value?"is-active":""}
            onClick={()=>setPayPeriod(p.value)}>{p.label}
          </button>
        ))}
      </div>

      {/* Money split — 3 hero boxes */}
      <div className="bc-grid bc-grid--3">
        <div className="bc-card bc-ops-money-card">
          <div className="bc-ops-money-icon" style={{background:"color-mix(in srgb,var(--c-ink) 8%,transparent)"}}>
            <Icon name="money" size={20} style={{color:"var(--c-ink)"}}/>
          </div>
          <div className="bc-ops-money-label">Total collected</div>
          <div className="bc-ops-money-amt">{egpK(totalCollected)}</div>
          <div className="bc-ops-money-sub">{periodOrders.length} paid orders</div>
        </div>
        <div className="bc-card bc-ops-money-card bc-ops-money-card--you">
          <div className="bc-ops-money-icon" style={{background:"color-mix(in srgb,var(--c-primary) 14%,transparent)"}}>
            <Icon name="verify" size={20} style={{color:"var(--c-primary-text)"}}/>
          </div>
          <div className="bc-ops-money-label">Your cut (BetyChef)</div>
          <div className="bc-ops-money-amt" style={{color:"var(--c-primary-text)"}}>{egpK(betychefCut)}</div>
          <div className="bc-ops-money-sub">{totalCollected>0?Math.round(betychefCut/totalCollected*100):0}% of total</div>
        </div>
        <div className="bc-card bc-ops-money-card">
          <div className="bc-ops-money-icon" style={{background:"color-mix(in srgb,var(--c-saffron) 18%,transparent)"}}>
            <Icon name="chefs" size={20} style={{color:"#7a6800"}}/>
          </div>
          <div className="bc-ops-money-label">Chefs' cut</div>
          <div className="bc-ops-money-amt">{egpK(chefsCut)}</div>
          <div className="bc-ops-money-sub">{totalCollected>0?Math.round(chefsCut/totalCollected*100):0}% of total</div>
        </div>
      </div>

      {/* Channel breakdown — donut + bars side by side */}
      <div className="bc-card">
        <div className="bc-card-head">
          <div>
            <h2 className="bc-card-title">Payment channels</h2>
            <p className="bc-card-sub">{periodOrders.length} paid orders · {PERIODS.find(p=>p.value===payPeriod)?.label}</p>
          </div>
        </div>
        <div className="bc-pay-layout">
          {/* Donut */}
          <DonutChart
            slices={methods.filter(m=>m.tx>0).map(m=>({...m, pct:m.pct}))}
            r={72}/>

          {/* Bars + details */}
          <div className="bc-pay-channels">
            {methods.map(m=>(
              <div key={m.key} className="bc-pay-channel-row">
                <div className="bc-pay-channel-head">
                  <span className="bc-pay-dot" style={{background:m.color,width:11,height:11}}/>
                  <span className="bc-pay-channel-name">{m.label}</span>
                  <span className="bc-pay-channel-pct" style={{color:m.color}}>{m.pct}%</span>
                </div>
                <div className="bc-pay-channel-bar">
                  <div style={{width:m.pct+"%", background:m.color, borderRadius:4, height:"100%", transition:"width .5s"}}/>
                </div>
                <div className="bc-pay-channel-meta">
                  <span>{m.tx} orders</span>
                  <span className="bc-strong">{egpK(m.value)}</span>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* ── SECTION 2: DELIVERY ── */}
      <div className="bc-ops-section-label" style={{marginTop:8}}>
        <Icon name="truck" size={16}/> Delivery
      </div>

      <div className="bc-grid bc-grid--3">
        <div className="bc-card bc-ops-delivery-card bc-ops-delivery-card--done">
          <div className="bc-ops-del-icon"><Icon name="check" size={22} stroke={2.5}/></div>
          <div className="bc-ops-del-num">{delivered}</div>
          <div className="bc-ops-del-label">Delivered</div>
          <div className="bc-ops-del-rate">{deliveryRate}% success rate</div>
        </div>

        <div className="bc-card bc-ops-delivery-card bc-ops-delivery-card--active">
          <div className="bc-ops-del-icon"><Icon name="truck" size={22}/></div>
          <div className="bc-ops-del-num">{inTransit}<span className="bc-livedot bc-livedot--lg" style={{marginLeft:8}}/></div>
          <div className="bc-ops-del-label">In progress now</div>
          <div className="bc-ops-del-rate">New · Preparing · On the way</div>
        </div>

        <div className="bc-card bc-ops-delivery-card bc-ops-delivery-card--fees">
          <div className="bc-ops-del-icon"><Icon name="money" size={22}/></div>
          <div className="bc-ops-del-num" style={{fontSize:22}}>TBD</div>
          <div className="bc-ops-del-label">Runners Co. fees</div>
          <div className="bc-ops-del-rate">Will be added once agreed</div>
        </div>
      </div>

      {/* Delivery breakdown by status */}
      <div className="bc-card">
        <div className="bc-card-head">
          <h2 className="bc-card-title">Delivery breakdown</h2>
          <Pill status="Connected" sm/>
        </div>
        <div className="bc-del-breakdown">
          {[
            { label:"Delivered",   n:delivered,  color:"var(--c-green)",   icon:"check"   },
            { label:"On the way",  n:allOrders.filter(o=>o.status==="On the way").length,  color:"var(--c-saffron)", icon:"truck"   },
            { label:"Ready",       n:allOrders.filter(o=>o.status==="Ready").length,       color:"var(--c-primary)", icon:"verify"  },
            { label:"Preparing",   n:allOrders.filter(o=>o.status==="Preparing").length,   color:"var(--c-ink-2)",   icon:"clock"   },
            { label:"New",         n:allOrders.filter(o=>o.status==="New").length,         color:"#5BA5C9",          icon:"orders"  },
            { label:"Cancelled",   n:cancelled,  color:"#C2410C",          icon:"x"       },
          ].map(row=>(
            <div key={row.label} className="bc-del-row">
              <span className="bc-del-ic" style={{background:row.color+"18",color:row.color}}>
                <Icon name={row.icon} size={14} stroke={2}/>
              </span>
              <span className="bc-del-label">{row.label}</span>
              <div className="bc-del-bar-wrap">
                <div className="bc-del-bar"
                  style={{width:allOrders.length?Math.max(row.n/allOrders.length*100,0)+"%":"0%",background:row.color}}/>
              </div>
              <span className="bc-del-n bc-strong">{row.n}</span>
              <span className="bc-del-pct bc-muted-cell">
                {allOrders.length?Math.round(row.n/allOrders.length*100):0}%
              </span>
            </div>
          ))}
        </div>
      </div>

    </div>
  );
}

/* ══════════════════════════════ CONTROLS ════════════════════════════════ */
function ControlsView() {
  const { feeTiers, orders: allOrders } = window.BC;

  // Fee tier adjustment
  const [tiers, setTiers] = useS((feeTiers||[]).map(t=>t.fee));

  // Manual order override
  const [overrideOrderId, setOverrideOrderId] = useS("");
  const [overrideNewValue, setOverrideNewValue] = useS("");
  const [overrideReason, setOverrideReason] = useS("");

  // Bulk adjust
  const [bulkChef, setBulkChef] = useS("All chefs");
  const [bulkType, setBulkType] = useS("discount");  // discount | fixed | percentage
  const [bulkAmount, setBulkAmount] = useS("");
  const [bulkReason, setBulkReason] = useS("");

  // Fee calculator
  const [calcOrderValue, setCalcOrderValue] = useS("");

  const feeFor = (v) => {
    const t = (feeTiers || []).find(tier => v > tier.min && v <= tier.max);
    return t ? t.fee : (feeTiers || [])[feeTiers.length - 1]?.fee || 0;
  };

  const calcFee = parseInt(calcOrderValue) || 0;
  const calcChefEarns = calcOrderValue ? calcOrderValue - feeFor(calcOrderValue) : 0;

  return (
    <div className="bc-stack">

      {/* ── 1. FEE TIER ADJUSTMENT ── */}
      <div className="bc-card">
        <div className="bc-card-head">
          <div><h2 className="bc-card-title">1. Platform fee tiers</h2>
            <p className="bc-card-sub">Adjust flat fees per order bracket</p>
          </div>
          <Icon name="money" size={20} style={{color:"var(--c-saffron)"}}/>
        </div>
        <div className="bc-tiers">
          {(feeTiers||[]).map((t,i)=>(
            <div className="bc-tier" key={t.range}>
              <div className="bc-tier-range">Order value <b>EGP {t.range}</b></div>
              <div className="bc-tier-fee">
                <button onClick={()=>setTiers(tiers.map((v,k)=>k===i?Math.max(0,v-5):v))}>–</button>
                <span>EGP {tiers[i]}</span>
                <button onClick={()=>setTiers(tiers.map((v,k)=>k===i?v+5:v))}>+</button>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* ── 2. MANUAL ORDER OVERRIDE ── */}
      <div className="bc-card">
        <div className="bc-card-head">
          <div><h2 className="bc-card-title">2. Override individual order</h2>
            <p className="bc-card-sub">Adjust single order value (refunds, disputes, etc.)</p>
          </div>
          <Icon name="edit" size={20} style={{color:"var(--c-primary)"}}/>
        </div>
        <div style={{display:"flex",flexDirection:"column",gap:"12px"}}>
          <label className="bc-field">
            <span className="bc-field-label">Order ID</span>
            <select className="bc-select bc-select--full" value={overrideOrderId} onChange={e=>setOverrideOrderId(e.target.value)}>
              <option value="">Select order to adjust...</option>
              {(allOrders||[]).slice(0,20).map(o=><option key={o.docId} value={o.docId}>{o.id} · {o.chef} · EGP {o.value}</option>)}
            </select>
          </label>
          {overrideOrderId && (
            <>
              <label className="bc-field">
                <span className="bc-field-label">New order value (EGP)</span>
                <input className="bc-input" type="number" value={overrideNewValue} onChange={e=>setOverrideNewValue(e.target.value)} placeholder="e.g. 200"/>
              </label>
              <label className="bc-field">
                <span className="bc-field-label">Reason for adjustment</span>
                <textarea className="bc-textarea" rows={2} value={overrideReason} onChange={e=>setOverrideReason(e.target.value)} placeholder="e.g. Customer refund, damage claim, dispute resolution"/>
              </label>
              <button className="bc-btn bc-btn--primary bc-tooltip" style={{width:"100%"}} data-tooltip="Adjust this order's value">Apply override</button>
            </>
          )}
        </div>
      </div>

      {/* ── 3. BULK ADJUST ORDERS ── */}
      <div className="bc-card">
        <div className="bc-card-head">
          <div><h2 className="bc-card-title">3. Bulk adjust orders</h2>
            <p className="bc-card-sub">Apply discount/adjustment to multiple orders at once</p>
          </div>
          <Icon name="broadcast" size={20} style={{color:"var(--c-green)"}}/>
        </div>
        <div style={{display:"flex",flexDirection:"column",gap:"12px"}}>
          <label className="bc-field">
            <span className="bc-field-label">Filter by chef</span>
            <select className="bc-select bc-select--full" value={bulkChef} onChange={e=>setBulkChef(e.target.value)}>
              <option value="All chefs">All chefs</option>
              {([...new Set((allOrders||[]).map(o=>o.chef))] || []).map(c=><option key={c}>{c}</option>)}
            </select>
          </label>
          <label className="bc-field">
            <span className="bc-field-label">Adjustment type</span>
            <select className="bc-select bc-select--full" value={bulkType} onChange={e=>setBulkType(e.target.value)}>
              <option value="discount">Discount (reduce fees)</option>
              <option value="percentage">Percentage off</option>
              <option value="fixed">Fixed fee override</option>
            </select>
          </label>
          <label className="bc-field">
            <span className="bc-field-label">{bulkType === "percentage" ? "Discount %" : "Amount (EGP)"}</span>
            <input className="bc-input" type="number" value={bulkAmount} onChange={e=>setBulkAmount(e.target.value)} placeholder={bulkType === "percentage" ? "e.g. 10" : "e.g. 5"}/>
          </label>
          <label className="bc-field">
            <span className="bc-field-label">Reason</span>
            <textarea className="bc-textarea" rows={2} value={bulkReason} onChange={e=>setBulkReason(e.target.value)} placeholder="e.g. Seasonal promotion, loyalty discount, compliance correction"/>
          </label>
          {bulkAmount && <div className="bc-result-bar"><b>{(allOrders||[]).filter(o=>bulkChef==="All chefs"||o.chef===bulkChef).length}</b> orders will be adjusted</div>}
          <button className="bc-btn bc-btn--primary bc-tooltip" style={{width:"100%"}} disabled={!bulkAmount} data-tooltip="Apply adjustment to all matching orders">Apply bulk adjustment</button>
        </div>
      </div>

      {/* ── 4. FEE CALCULATOR ── */}
      <div className="bc-card">
        <div className="bc-card-head">
          <div><h2 className="bc-card-title">4. Fee calculator (predictor)</h2>
            <p className="bc-card-sub">See fee breakdown before confirming an order</p>
          </div>
          <Icon name="chart" size={20} style={{color:"var(--c-primary)"}}/>
        </div>
        <div style={{display:"flex",flexDirection:"column",gap:"14px"}}>
          <label className="bc-field">
            <span className="bc-field-label">Order value (EGP)</span>
            <input className="bc-input" type="number" value={calcOrderValue} onChange={e=>setCalcOrderValue(e.target.value)} placeholder="e.g. 350" autoFocus/>
          </label>

          {calcOrderValue && (
            <>
              <div style={{background:"var(--c-surface-2)",borderRadius:"12px",padding:"16px"}}>
                <div style={{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"12px"}}>
                  {/* Money flow */}
                  <div style={{textAlign:"center",padding:"12px",background:"var(--c-surface)",borderRadius:"10px"}}>
                    <div style={{fontSize:"11px",color:"var(--c-ink-2)",textTransform:"uppercase",fontWeight:600,marginBottom:"4px"}}>Customer pays</div>
                    <div style={{fontFamily:"var(--font-mono)",fontSize:"20px",fontWeight:700,color:"var(--c-ink)"}}>EGP {calcOrderValue}</div>
                  </div>

                  <div style={{textAlign:"center",padding:"12px",background:"var(--c-surface)",borderRadius:"10px"}}>
                    <div style={{fontSize:"11px",color:"var(--c-ink-2)",textTransform:"uppercase",fontWeight:600,marginBottom:"4px"}}>Your fee</div>
                    <div style={{fontFamily:"var(--font-mono)",fontSize:"20px",fontWeight:700,color:"var(--c-saffron)"}}>EGP {feeFor(calcOrderValue)}</div>
                  </div>

                  <div style={{textAlign:"center",padding:"12px",background:"var(--c-surface)",borderRadius:"10px",gridColumn:"span 2"}}>
                    <div style={{fontSize:"11px",color:"var(--c-ink-2)",textTransform:"uppercase",fontWeight:600,marginBottom:"4px"}}>Chef earns</div>
                    <div style={{fontFamily:"var(--font-mono)",fontSize:"22px",fontWeight:700,color:"var(--c-green)"}}>EGP {calcChefEarns}</div>
                  </div>
                </div>
              </div>

              {/* Percentage breakdown */}
              <div style={{fontSize:"13px",color:"var(--c-ink-2)",lineHeight:"1.6"}}>
                <div style={{display:"flex",justifyContent:"space-between",marginBottom:"6px"}}>
                  <span>Your cut</span>
                  <b style={{color:"var(--c-ink)"}}>{((feeFor(calcOrderValue)/calcOrderValue)*100).toFixed(1)}%</b>
                </div>
                <div style={{display:"flex",justifyContent:"space-between"}}>
                  <span>Chef gets</span>
                  <b style={{color:"var(--c-ink)"}}>{((calcChefEarns/calcOrderValue)*100).toFixed(1)}%</b>
                </div>
              </div>
            </>
          )}
        </div>
      </div>

    </div>
  );
}

/* ══════════════════════════════ NOTIFICATIONS ═══════════════════════════ */
const AREAS = ["All Cairo","Maadi","Nasr City","Heliopolis","New Cairo","6th of October","Sheikh Zayed","Alexandria"];
const CATEGORIES = ["All categories","Molokhia","Mahshi","Koshari","Béchamel","Grilled","Seafood","Sweets","Breakfast"];

function NotificationsView() {
  const { can } = usePermissions();
  const canSend = can("notifications","send");
  const { notifications, chefs: allChefs, customers: allCustomers } = window.BC;
  const [mode,      setMode]      = useS("broadcast");    // broadcast | specific
  const [who,       setWho]       = useS("chefs");        // chefs | customers
  const [title,     setTitle]     = useS("");
  const [body,      setBody]      = useS("");
  const [sending,   setSending]   = useS(false);
  const [sent,      setSent]      = useS(false);

  // Filters for chefs
  const [chefStatus,   setChefStatus]   = useS("All");
  const [chefArea,     setChefArea]     = useS("All areas");
  const [chefRating,   setChefRating]   = useS("All ratings");
  const [chefHealth,   setChefHealth]   = useS("All health");
  const [chefMinOrders,setChefMinOrders]= useS("0");
  const [chefSelected, setChefSelected] = useS({});

  // Filters for customers
  const [custType,     setCustType]     = useS("All");
  const [custArea,     setCustArea]     = useS("All areas");
  const [custMinSpend, setCustMinSpend] = useS("0");
  const [custSelected, setCustSelected] = useS({});

  const broadcastTargets = [
    { value:"all",     label:"Everyone (chefs + customers)" },
    { value:"chefs",   label:"All chefs" },
    { value:"customers", label:"All customers" },
  ];

  // Filter chefs
  const filteredChefs = useMemo(() => {
    let result = allChefs || [];
    if (chefStatus !== "All") result = result.filter(c => c.status === chefStatus);
    if (chefArea !== "All areas") result = result.filter(c => c.area === chefArea);
    if (chefRating !== "All ratings") {
      const r = parseFloat(chefRating) || 0;
      if (chefRating === "4.5+") result = result.filter(c => parseFloat(c.rating) >= 4.5);
      else if (chefRating === "4.0+") result = result.filter(c => parseFloat(c.rating) >= 4.0);
      else if (chefRating === "3.0+") result = result.filter(c => parseFloat(c.rating) >= 3.0);
      else if (chefRating === "Unrated") result = result.filter(c => !c.rating);
    }
    if (chefHealth !== "All health") {
      const h = chefHealth.toLowerCase().replace(" ","");
      const map = { "TopChef":"great", "Good":"good", "Growing":"growing", "Inactive":"inactive", "New":"new" };
      result = result.filter(c => c.health === map[chefHealth.replace(" ","")]);
    }
    const minOrders = parseInt(chefMinOrders) || 0;
    if (minOrders > 0) result = result.filter(c => (c.orders || 0) >= minOrders);
    return result;
  }, [allChefs, chefStatus, chefArea, chefRating, chefHealth, chefMinOrders]);

  // Filter customers
  const filteredCustomers = useMemo(() => {
    let result = allCustomers || [];
    if (custType !== "All") result = result.filter(c => custType === "Repeat" ? c.repeat : !c.repeat);
    if (custArea !== "All areas") result = result.filter(c => c.area === custArea);
    const minSpend = parseInt(custMinSpend) || 0;
    if (minSpend > 0) result = result.filter(c => (c.spend || 0) >= minSpend);
    return result;
  }, [allCustomers, custType, custArea, custMinSpend]);

  const filtered = who === "chefs" ? filteredChefs : filteredCustomers;

  // Count selected
  const selectedList = who === "chefs" ? chefSelected : custSelected;
  const selectedCount = Object.values(selectedList).filter(Boolean).length;
  const recipientCount = mode === "broadcast" ? filtered.length : selectedCount;

  async function send(e) {
    e.preventDefault();
    if (!title || !body) return;
    if (mode === "specific" && selectedCount === 0) { alert("Please select at least one recipient"); return; }

    setSending(true);
    try {
      const targetIds = mode === "specific" ? Object.keys(selectedList).filter(k => selectedList[k]) : null;
      await window.BC_actions.sendNotification({
        title, body,
        target: mode === "broadcast" ? who : "specific",
        targetIds,
        filters: mode === "broadcast" ? (who === "chefs" ? {status:chefStatus,area:chefArea,rating:chefRating,health:chefHealth,minOrders:chefMinOrders} : {type:custType,area:custArea,minSpend:custMinSpend}) : null
      });
      setSent(true); setTitle(""); setBody("");
      setTimeout(()=>setSent(false), 3000);
    } catch(e) { alert(e.message); }
    setSending(false);
  }

  const msgChars = body.length;
  const msgLines = body.split('\n').length;
  const msgOk = msgLines <= 2 && msgChars <= 160;

  return (
    <div className="bc-stack">
      <div className="bc-card">
        <div className="bc-card-head">
          <div><h2 className="bc-card-title">Send a notification</h2>
            <p className="bc-card-sub">Push notifications to chefs & customers</p>
          </div>
          <Icon name="notify" size={20} style={{color:"var(--c-primary)"}}/>
        </div>

        <form onSubmit={send} className="bc-compose-form">
          {/* Mode selector */}
          <div className="bc-form-row">
            <label className="bc-field"><span className="bc-field-label">Send mode</span>
              <select className="bc-select" value={mode} onChange={e=>setMode(e.target.value)}>
                <option value="broadcast">Broadcast (with filters)</option>
                <option value="specific">Hand-pick recipients</option>
              </select>
            </label>
          </div>

          {/* Who */}
          <div className="bc-form-row">
            <label className="bc-field"><span className="bc-field-label">Who to send to</span>
              <select className="bc-select" value={who} onChange={e=>{setWho(e.target.value);setChefSelected({});setCustSelected({});}}>
                <option value="chefs">Chefs</option>
                <option value="customers">Customers</option>
              </select>
            </label>
          </div>

          {/* Chef filters */}
          {who === "chefs" && (
            <>
              <div className="bc-form-row">
                <label className="bc-field"><span className="bc-field-label">Status</span>
                  <select className="bc-select" value={chefStatus} onChange={e=>setChefStatus(e.target.value)}>
                    {["All","Joined","Active","Paused"].map(s=><option key={s}>{s}</option>)}
                  </select>
                </label>
                <label className="bc-field"><span className="bc-field-label">Area</span>
                  <select className="bc-select" value={chefArea} onChange={e=>setChefArea(e.target.value)}>
                    {["All areas","Cairo","Maadi","Nasr City","Heliopolis","New Cairo","6th of October","Sheikh Zayed","Alexandria"].map(a=><option key={a}>{a}</option>)}
                  </select>
                </label>
              </div>
              <div className="bc-form-row">
                <label className="bc-field"><span className="bc-field-label">Rating</span>
                  <select className="bc-select" value={chefRating} onChange={e=>setChefRating(e.target.value)}>
                    {["All ratings","4.5+","4.0+","3.0+","Unrated"].map(r=><option key={r}>{r}</option>)}
                  </select>
                </label>
                <label className="bc-field"><span className="bc-field-label">Health</span>
                  <select className="bc-select" value={chefHealth} onChange={e=>setChefHealth(e.target.value)}>
                    {["All health","Top chef","Good","Growing","Inactive","New"].map(h=><option key={h}>{h}</option>)}
                  </select>
                </label>
              </div>
              <div className="bc-form-row">
                <label className="bc-field"><span className="bc-field-label">Min orders</span>
                  <input className="bc-input" type="number" value={chefMinOrders} onChange={e=>setChefMinOrders(e.target.value)} placeholder="0"/>
                </label>
              </div>
            </>
          )}

          {/* Customer filters */}
          {who === "customers" && (
            <>
              <div className="bc-form-row">
                <label className="bc-field"><span className="bc-field-label">Type</span>
                  <select className="bc-select" value={custType} onChange={e=>setCustType(e.target.value)}>
                    {["All","Repeat","New"].map(t=><option key={t}>{t}</option>)}
                  </select>
                </label>
                <label className="bc-field"><span className="bc-field-label">Area</span>
                  <select className="bc-select" value={custArea} onChange={e=>setCustArea(e.target.value)}>
                    {["All areas","Cairo","Maadi","Nasr City","Heliopolis","New Cairo","6th of October","Sheikh Zayed","Alexandria"].map(a=><option key={a}>{a}</option>)}
                  </select>
                </label>
              </div>
              <div className="bc-form-row">
                <label className="bc-field"><span className="bc-field-label">Min lifetime spend (EGP)</span>
                  <input className="bc-input" type="number" value={custMinSpend} onChange={e=>setCustMinSpend(e.target.value)} placeholder="0"/>
                </label>
              </div>
            </>
          )}

          {/* Recipients list for hand-pick mode */}
          {mode === "specific" && (
            <div className="bc-notify-recipients">
              <div style={{fontSize:13,fontWeight:600,marginBottom:8}}>Select recipients ({selectedCount} chosen)</div>
              <div className="bc-notify-list">
                {filtered.map(item=>(
                  <label key={item.docId} className="bc-notify-item">
                    <input type="checkbox"
                      checked={selectedList[item.docId]||false}
                      onChange={e=>{
                        const newSel = {...selectedList};
                        if(e.target.checked) newSel[item.docId]=true;
                        else delete newSel[item.docId];
                        who==="chefs"?setChefSelected(newSel):setCustSelected(newSel);
                      }}/>
                    <span>{item.name}</span>
                    {who==="chefs" && <span className="bc-notify-meta">{item.area} · {item.status}</span>}
                    {who==="customers" && <span className="bc-notify-meta">{item.area} · {item.repeat?"Repeat":"New"}</span>}
                  </label>
                ))}
              </div>
            </div>
          )}

          {/* Message */}
          <label className="bc-field"><span className="bc-field-label">Title</span>
            <input className="bc-input" value={title} onChange={e=>setTitle(e.target.value)}
              placeholder="e.g. New feature available!" maxLength={80}/></label>

          <label className="bc-field"><span className="bc-field-label">Message (max 2 lines)</span>
            <textarea className="bc-textarea" rows={2} value={body} onChange={e=>setBody(e.target.value.slice(0,160))}
              placeholder="Your message…" style={{resize:"none"}}/>
            <div style={{fontSize:12,color:msgOk?"var(--c-ink-2)":"#C2410C",marginTop:4}}>
              {msgChars}/160 chars · {msgLines} line{msgLines!==1?"s":""} {!msgOk && "— max 2 lines, 160 chars"}
            </div>
          </label>

          {/* Send button */}
          <div className="bc-compose-actions">
            {sent && <span style={{color:"var(--c-green)",fontWeight:600}}>Sent ✓ to {recipientCount} recipient{recipientCount!==1?"s":""}</span>}
            {!canSend && <span style={{color:"var(--c-ink-2)",fontSize:13}}>View only — your role can't send notifications.</span>}
            {canSend && (
            <button className="bc-btn bc-btn--primary" type="submit" disabled={sending||!title||!body||!msgOk||recipientCount===0}>
              <Icon name="send" size={15}/>{sending?`Sending to ${recipientCount}…`:`Send to ${recipientCount}`}
            </button>
            )}
          </div>
        </form>
      </div>

      {/* History */}
      <div className="bc-card">
        <div className="bc-card-head"><h2 className="bc-card-title">Sent notifications</h2></div>
        {(!notifications||notifications.length===0)
          ? <div className="bc-empty">No notifications sent yet.</div>
          : <div className="bc-broadcasts">
            {notifications.map((n,i)=>(
              <div key={n.docId||i} className="bc-broadcast">
                <span className="bc-bc-ic"><Icon name="notify" size={16}/></span>
                <div className="bc-bc-main">
                  <div className="bc-bc-title">{n.title}</div>
                  <div className="bc-bc-meta">{n.body}</div>
                </div>
                <div style={{textAlign:"right",flexShrink:0}}>
                  <div className="bc-bc-when">{n.sentAt}</div>
                  <div style={{fontSize:11,color:"var(--c-ink-2)",marginTop:2}}>To: {n.target}</div>
                </div>
              </div>
            ))}
          </div>
        }
      </div>
    </div>
  );
}

/* ══════════════════════════════ OUTREACH / CRM ══════════════════════════ */
const PROSPECT_STATUSES = ["New lead","Contacted","Agreed","Declined","Registered"];

function CRMView() {
  const { can } = usePermissions();
  const { prospects } = window.BC;
  const [addOpen,  setAddOpen]  = useS(false);
  const [editItem, setEditItem] = useS(null);
  const [filter,   setFilter]   = useS("All");
  const [repFilter, setRepFilter] = useS("All reps");

  // Unique reps (people who added prospects)
  const reps = useMemo(()=>{
    const s = new Set((prospects||[]).map(p=>p.createdBy).filter(Boolean));
    return ["All reps", ...Array.from(s).sort()];
  }, [prospects]);

  const filtered = useMemo(()=>
    (prospects||[]).filter(p=>
      (filter==="All"||p.status===filter) &&
      (repFilter==="All reps"||p.createdBy===repFilter)
    ),
    [prospects, filter, repFilter]
  );

  const stats = useMemo(()=>({
    total:      (prospects||[]).length,
    agreed:     (prospects||[]).filter(p=>p.agreed||p.status==="Agreed").length,
    registered: (prospects||[]).filter(p=>p.status==="Registered"||p.converted).length,
    rate:       (prospects||[]).length
      ? Math.round((prospects||[]).filter(p=>p.agreed||p.status==="Agreed").length/(prospects||[]).length*100) : 0,
  }), [prospects]);

  // Per-rep performance leaderboard
  const repStats = useMemo(()=>{
    const map = {};
    (prospects||[]).forEach(p=>{
      const who = p.createdBy || "Founder";
      const r = map[who] || { name:who, added:0, agreed:0, registered:0 };
      r.added += 1;
      if (p.agreed||p.status==="Agreed") r.agreed += 1;
      if (p.status==="Registered"||p.converted) r.registered += 1;
      map[who] = r;
    });
    return Object.values(map)
      .map(r=>({ ...r, rate: r.added ? Math.round(r.agreed/r.added*100) : 0 }))
      .sort((a,b)=>b.agreed-a.agreed || b.added-a.added);
  }, [prospects]);

  function downloadCSV() {
    if (!(prospects||[]).length) return alert("No prospects to download");
    const headers = ["Name","Phone","Kitchen","Area","Status","Agreed","Added by","Notes","Date"];
    const rows = (prospects||[]).map(p=>[
      p.name, p.phone, p.kitchenName, p.area, p.status,
      p.agreed?"Yes":"No", p.createdBy||"", p.notes, p.date,
    ].map(v=>`"${String(v||"").replace(/"/g,'""')}"`));
    const csv = [headers.join(","), ...rows.map(r=>r.join(","))].join("\n");
    const blob = new Blob(["﻿"+csv], {type:"text/csv;charset=utf-8"});
    const url  = URL.createObjectURL(blob);
    const a    = document.createElement("a");
    a.href = url; a.download = "betychef-outreach.csv"; a.click();
    URL.revokeObjectURL(url);
  }

  return (
    <div className="bc-stack">
      <div className="bc-grid bc-grid--3">
        <div className="bc-card bc-stat">
          <span className="bc-kpi-label">Total prospects</span>
          <div className="bc-kpi-value">{stats.total}</div>
          <span className="bc-stat-delta">chefs you've talked to</span>
        </div>
        <div className="bc-card bc-stat">
          <span className="bc-kpi-label">Agreed to join</span>
          <div className="bc-kpi-value">{stats.agreed} <span style={{fontSize:16,color:"var(--c-ink-2)"}}>({stats.rate}%)</span></div>
          <span className="bc-stat-delta">conversion rate</span>
        </div>
        <div className="bc-card bc-stat bc-stat--accent">
          <span className="bc-kpi-label">Registered in app</span>
          <div className="bc-kpi-value">{stats.registered}</div>
          <span className="bc-stat-delta">made it to the platform</span>
        </div>
      </div>

      {/* Team performance leaderboard */}
      {repStats.length > 0 && (
        <div className="bc-card">
          <div className="bc-card-head">
            <div><h2 className="bc-card-title">Team performance</h2>
              <p className="bc-card-sub">Who's bringing in — and converting — chefs</p>
            </div>
            <Icon name="crm" size={20} style={{color:"var(--c-primary)"}}/>
          </div>
          <div style={{overflowX:"auto"}}>
            <table className="bc-table">
              <thead>
                <tr><th>Rep</th><th className="num">Leads added</th>
                  <th className="num">Agreed</th><th className="num">Registered</th>
                  <th className="num">Conversion</th>
                </tr>
              </thead>
              <tbody>
                {repStats.map((r,i)=>(
                  <tr key={r.name} onClick={()=>setRepFilter(r.name)} style={{cursor:"pointer"}}>
                    <td>
                      <div className="bc-recipe-cell">
                        <Avatar name={r.name} kind="cust"/>
                        <div className="bc-recipe-name">
                          {i===0 && r.agreed>0 ? "🏆 " : ""}{r.name}
                        </div>
                      </div>
                    </td>
                    <td className="num bc-strong">{r.added}</td>
                    <td className="num" style={{color:"var(--c-green)"}}>{r.agreed}</td>
                    <td className="num">{r.registered}</td>
                    <td className="num">
                      <span style={{fontWeight:700, color: r.rate>=50?"var(--c-green)":r.rate>=25?"#7a6800":"var(--c-ink-2)"}}>
                        {r.rate}%
                      </span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      <div className="bc-toolbar">
        <div className="bc-segmented bc-segmented--scroll">
          {["All",...PROSPECT_STATUSES].map(s=>(
            <button key={s} className={filter===s?"is-active":""} onClick={()=>setFilter(s)}>
              {s}{s!=="All"&&<span className="bc-seg-count">{(prospects||[]).filter(p=>p.status===s).length}</span>}
            </button>
          ))}
        </div>
        <div style={{display:"flex",gap:8}}>
          {reps.length>2 && (
            <select className="bc-select" value={repFilter} onChange={e=>setRepFilter(e.target.value)}>
              {reps.map(r=><option key={r}>{r}</option>)}
            </select>
          )}
          {can("outreach","export") && (
            <button className="bc-btn" onClick={downloadCSV}>
              <Icon name="download" size={15}/>Export CSV
            </button>
          )}
          {can("outreach","addToProspect") && (
            <button className="bc-btn bc-btn--primary" onClick={()=>setAddOpen(true)}>
              <Icon name="plus" size={16} stroke={2.2}/>Add prospect
            </button>
          )}
        </div>
      </div>

      <div className="bc-card" style={{padding:0,overflow:"hidden"}}>
        <div style={{overflowX:"auto"}}>
          <table className="bc-table">
            <thead>
              <tr><th>Name</th><th>Mobile</th><th>Kitchen</th><th>Area</th>
                <th>Status</th><th>Agreed?</th><th>Added by</th><th>Added</th><th>Notes</th><th></th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(p=>(
                <tr key={p.docId} onClick={()=>setEditItem(p)} style={{cursor:"pointer"}}>
                  <td className="bc-strong">{p.name||"—"}</td>
                  <td className="bc-muted-cell">{p.phone||"—"}</td>
                  <td className="bc-muted-cell">{p.kitchenName||"—"}</td>
                  <td className="bc-muted-cell">{p.area&&<span className="bc-area-tag"><Icon name="pin" size={12}/>{p.area}</span>}</td>
                  <td><span className={"bc-pill bc-pill--"+(p.status==="Agreed"||p.status==="Registered"?"ok":p.status==="Contacted"?"warn":p.status==="Declined"?"bad":"muted")+" bc-pill--sm"}>{p.status}</span></td>
                  <td className="num">{p.agreed?"✅":"—"}</td>
                  <td className="bc-muted-cell"><span className="bc-rep-tag"><Icon name="user" size={11}/>{p.createdBy||"—"}</span></td>
                  <td className="bc-muted-cell">{p.date}</td>
                  <td className="bc-muted-cell bc-specialties">{p.notes||"—"}</td>
                  <td><Icon name="edit" size={14} style={{opacity:.4}}/></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        {filtered.length===0 && (
          <div className="bc-empty">
            {!(prospects||[]).length
              ? "No prospects yet — start adding the chefs you've been talking to!"
              : "No prospects in this stage."}
          </div>
        )}
      </div>

      <Modal open={addOpen} onClose={()=>setAddOpen(false)} title="Add prospect" wide>
        <ProspectForm onClose={()=>setAddOpen(false)}/>
      </Modal>
      <Modal open={!!editItem} onClose={()=>setEditItem(null)} title={editItem?.name||"Edit"} wide>
        {editItem && <ProspectForm existing={editItem} onClose={()=>setEditItem(null)}/>}
      </Modal>
    </div>
  );
}

function ProspectForm({ existing, onClose }) {
  const [form, setForm] = useS(existing||{name:"",phone:"",kitchenName:"",area:"",status:"New lead",agreed:false,notes:""});
  const [saving, setSaving] = useS(false);
  const set = k => e => setForm(f=>({...f,[k]:e.target.value}));

  async function submit(e) {
    e.preventDefault(); setSaving(true);
    try {
      existing
        ? await window.BC_actions.updateProspect(existing.docId, form)
        : await window.BC_actions.addProspect(form);
      onClose();
    } catch(e) { alert(e.message); }
    setSaving(false);
  }

  return (
    <form onSubmit={submit} className="bc-compose-form">
      {existing && existing.createdBy && (
        <div className="bc-rep-tag" style={{alignSelf:"flex-start"}}>
          <Icon name="user" size={12}/>Added by {existing.createdBy}{existing.date && existing.date!=="—" ? " · "+existing.date : ""}
        </div>
      )}
      <div className="bc-form-row">
        <label className="bc-field"><span className="bc-field-label">Name</span>
          <input className="bc-input" value={form.name||""} onChange={set("name")} placeholder="Chef name" autoFocus/></label>
        <label className="bc-field"><span className="bc-field-label">Mobile</span>
          <input className="bc-input" value={form.phone||""} onChange={set("phone")} placeholder="01x xxxx xxxx"/></label>
      </div>
      <div className="bc-form-row">
        <label className="bc-field"><span className="bc-field-label">Kitchen name</span>
          <input className="bc-input" value={form.kitchenName||""} onChange={set("kitchenName")} placeholder="Kitchen name"/></label>
        <label className="bc-field"><span className="bc-field-label">Area</span>
          <input className="bc-input" value={form.area||""} onChange={set("area")} placeholder="Maadi, Cairo"/></label>
      </div>
      <div className="bc-form-row">
        <label className="bc-field"><span className="bc-field-label">Status</span>
          <select className="bc-select bc-select--full" value={form.status||"New lead"} onChange={set("status")}>
            {PROSPECT_STATUSES.map(s=><option key={s}>{s}</option>)}
          </select>
        </label>
        <label className="bc-field" style={{flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:10,paddingBottom:4}}>
          <span className="bc-field-label">Agreed to join?</span>
          <input type="checkbox" checked={!!form.agreed} onChange={e=>setForm(f=>({...f,agreed:e.target.checked}))}
            style={{width:18,height:18,accentColor:"var(--c-primary)"}}/>
        </label>
      </div>
      <label className="bc-field"><span className="bc-field-label">Notes</span>
        <textarea className="bc-textarea" rows={3} value={form.notes||""} onChange={set("notes")} placeholder="Any notes…"/></label>
      <div className="bc-compose-actions">
        {existing && <button type="button" className="bc-btn bc-btn--danger"
          onClick={async()=>{ if(!confirm("Remove?"))return; await window.BC_actions.deleteProspect(existing.docId); onClose(); }}>
          <Icon name="trash" size={14}/>Remove</button>}
        <button type="button" className="bc-btn" onClick={onClose}>Cancel</button>
        <button type="submit" className="bc-btn bc-btn--primary" disabled={saving}>
          {saving?"Saving…":existing?"Save changes":"Add prospect"}
        </button>
      </div>
    </form>
  );
}

/* ══════════════════════════════ APPLICATIONS ════════════════════════════ */
// Chef application review queue. Reads the app's status contract
// (pending | rejected) + appeals, and writes approved/rejected back.
const APP_AGING_DAYS = 2;  // flag an application "waiting too long" after this

function ApplicationsView({ query, navigate }) {
  const { can } = usePermissions();
  const showTestData = useShowTestData();
  const [tab, setTab]         = useS("pending");   // pending | appeals | rejected
  const [detail, setDetail]   = useS(null);
  const [rejecting, setRejecting] = useS(null);     // chef pending a rejection reason
  const [, setTick]           = useS(0);

  React.useEffect(() => {
    const h = () => setTick(t => t+1);
    window.addEventListener("testAccountsChanged", h);
    return () => window.removeEventListener("testAccountsChanged", h);
  }, []);

  const canReview = can("chefs","approve");

  const all = useMemo(() => {
    let list = window.BC.chefs || [];
    if (!showTestData && window.BC_testAccounts)
      list = list.filter(c => !window.BC_testAccounts.isTestChef(c.docId));
    return list;
  }, [window.BC.chefs, showTestData]);

  const now = Date.now();
  const ageDays = c => c.joinedAt ? Math.floor((now - tsMs(c.joinedAt)) / 86400000) : 0;
  const ageLabel = c => {
    if (!c.joinedAt) return "—";
    const d = ageDays(c);
    if (d === 0) return "Today";
    if (d === 1) return "1 day";
    return d + " days";
  };

  const pending  = all.filter(c => c.status === "Pending").sort((a,b)=>tsMs(a.joinedAt)-tsMs(b.joinedAt)); // oldest first = most urgent
  const rejected = all.filter(c => c.status === "Rejected").sort((a,b)=>tsMs(b.joinedAt)-tsMs(a.joinedAt));
  const appeals  = rejected.filter(c => c.appealMessage);
  const oldestPending = pending.length ? ageDays(pending[0]) : 0;

  const q = (query||"").toLowerCase();
  const filterQ = list => !q ? list : list.filter(c => (c.name+c.area+c.kitchenName+(c.email||"")).toLowerCase().includes(q));

  const tabList = tab==="pending" ? filterQ(pending) : tab==="appeals" ? filterQ(appeals) : filterQ(rejected);

  async function approve(c){ await window.BC_actions.approveChef(c.docId); setDetail(null); }
  async function doReject(c, reason){ await window.BC_actions.rejectChef(c.docId, reason); setRejecting(null); setDetail(null); }

  return (
    <div className="bc-stack">

      {/* ── Stats ── */}
      <div className="bc-chef-stats-grid">
        <div className="bc-chef-stat-card bc-chef-stat-card--joined" onClick={()=>setTab("pending")} style={{cursor:"pointer"}}>
          <div className="bc-cstat-dot" style={{background:"var(--c-saffron)"}}/>
          <div className="bc-cstat-num" style={{color:"#7a6800"}}>{pending.length}</div>
          <div className="bc-cstat-label">Pending review</div>
          <div className="bc-cstat-sub">{pending.length>0?"tap to review":"all clear ✓"}</div>
        </div>
        <div className="bc-chef-stat-card" style={oldestPending>=APP_AGING_DAYS?{border:"1px solid color-mix(in srgb,#C2410C 45%,transparent)"}:{}}>
          <div className="bc-cstat-num" style={{color:oldestPending>=APP_AGING_DAYS?"#C2410C":"var(--c-ink)"}}>
            {oldestPending}<span style={{fontSize:14,fontWeight:600}}> day{oldestPending!==1?"s":""}</span>
          </div>
          <div className="bc-cstat-label">Longest waiting</div>
          <div className="bc-cstat-sub">{oldestPending>=APP_AGING_DAYS?"⚠ needs attention":"within target"}</div>
        </div>
        <div className="bc-chef-stat-card" onClick={()=>setTab("appeals")} style={{cursor:"pointer"}}>
          <div className="bc-cstat-dot" style={{background:"#5BA5C9"}}/>
          <div className="bc-cstat-num" style={{color: appeals.length?"#2E6F8E":"var(--c-ink)"}}>{appeals.length}</div>
          <div className="bc-cstat-label">Appeals</div>
          <div className="bc-cstat-sub">{appeals.length>0?"disputes to reconsider":"none"}</div>
        </div>
        <div className="bc-chef-stat-card" onClick={()=>setTab("rejected")} style={{cursor:"pointer"}}>
          <div className="bc-cstat-dot" style={{background:"#C2410C"}}/>
          <div className="bc-cstat-num">{rejected.length}</div>
          <div className="bc-cstat-label">Rejected</div>
          <div className="bc-cstat-sub">tap to view</div>
        </div>
        <div className="bc-chef-stat-card bc-chef-stat-card--active" onClick={()=>navigate&&navigate("chefs")} style={{cursor:"pointer"}}>
          <div className="bc-cstat-dot" style={{background:"var(--c-green)"}}/>
          <div className="bc-cstat-num" style={{color:"var(--c-green)"}}>{(window.BC.northStar&&window.BC.northStar.active)||0}</div>
          <div className="bc-cstat-label">Approved & live</div>
          <div className="bc-cstat-sub">view chef network →</div>
        </div>
      </div>

      {/* ── Tabs ── */}
      <div className="bc-toolbar">
        <div className="bc-segmented bc-segmented--scroll">
          {[["pending","Pending",pending.length],["appeals","Appeals",appeals.length],["rejected","Rejected",rejected.length]].map(([id,label,n])=>(
            <button key={id} className={tab===id?"is-active":""} onClick={()=>setTab(id)}>
              {label}<span className="bc-seg-count">{n}</span>
            </button>
          ))}
        </div>
      </div>

      {/* ── List ── */}
      <div className="bc-card" style={{padding:0,overflow:"hidden"}}>
        <div style={{overflowX:"auto"}}>
          <table className="bc-table bc-table--analytics">
            <thead>
              <tr>
                <th style={{minWidth:200}}>Applicant</th>
                <th>Kitchen</th>
                <th>Area</th>
                <th>Categories</th>
                <th>{tab==="pending"?"Waiting":"Submitted"}</th>
                {tab!=="pending" && <th>Reason</th>}
                <th></th>
              </tr>
            </thead>
            <tbody>
              {tabList.map(c=>{
                const old = tab==="pending" && ageDays(c)>=APP_AGING_DAYS;
                return (
                  <tr key={c.docId} onClick={()=>setDetail(c)} style={{cursor:"pointer"}}>
                    <td>
                      <div className="bc-recipe-cell">
                        <Avatar name={c.name} photoUrl={c.kitchenImage||null}/>
                        <div>
                          <div className="bc-recipe-name">{c.name}{tab==="appeals" && <span style={{marginLeft:6,fontSize:11,color:"#2E6F8E",fontWeight:700}}>· appealed</span>}</div>
                          <div className="bc-recipe-id">{c.mobile||c.email||c.id}</div>
                        </div>
                      </div>
                    </td>
                    <td className="bc-muted-cell">{c.kitchenName||"—"}</td>
                    <td className="bc-muted-cell"><span className="bc-area-tag"><Icon name="pin" size={12}/>{c.area}</span></td>
                    <td className="bc-muted-cell bc-specialties">{(c.categories||[]).slice(0,2).join(", ")||"—"}</td>
                    <td>
                      <span style={{fontWeight:600, color: old?"#C2410C":"var(--c-ink-2)"}}>
                        {old && "⚠ "}{ageLabel(c)}
                      </span>
                    </td>
                    {tab!=="pending" && <td className="bc-muted-cell bc-specialties">{c.rejectionReason||"—"}</td>}
                    <td><Icon name="chevron" size={16} style={{opacity:.4}}/></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
        {tabList.length===0 && (
          <div className="bc-empty">
            {tab==="pending" ? "No applications waiting — you're all caught up ✓"
             : tab==="appeals" ? "No appeals to reconsider."
             : "No rejected applications."}
          </div>
        )}
      </div>

      {/* Detail modal */}
      <Modal open={!!detail} onClose={()=>setDetail(null)} title={detail?.name||"Application"} wide>
        {detail && <ApplicationDetail c={detail} canReview={canReview}
          onApprove={()=>approve(detail)} onReject={()=>setRejecting(detail)} ageLabel={ageLabel(detail)}/>}
      </Modal>

      {/* Reject reason modal */}
      <Modal open={!!rejecting} onClose={()=>setRejecting(null)} title={"Reject "+(rejecting?.name||"")}>
        {rejecting && <RejectForm chef={rejecting} onCancel={()=>setRejecting(null)} onConfirm={(reason)=>doReject(rejecting, reason)}/>}
      </Modal>
    </div>
  );
}

/* Full application entry + review actions */
function ApplicationDetail({ c, canReview, onApprove, onReject, ageLabel }) {
  const rows = [
    c.mobile      && { label:"Mobile",         value: c.mobile },
    c.email       && { label:"Email",          value: c.email },
    c.address     && { label:"Address",        value: c.address },
    c.kitchenName && { label:"Kitchen",        value: c.kitchenName },
    c.workHours   && { label:"Working hours",  value: c.workHours },
    c.instaPay    && { label:"InstaPay",       value: c.instaPay },
    c.nationalId  && { label:"National ID",    value: c.nationalId },
  ].filter(Boolean);

  return (
    <div className="bc-cpop">
      <div className="bc-cpop-top">
        <Avatar name={c.name} kind="chef" size="lg" photoUrl={c.kitchenImage||null}/>
        <div className="bc-cpop-top-info">
          <div className="bc-cpop-status-row">
            <span className="bc-cpop-dot" style={{background: c.status==="Pending"?"var(--c-saffron)":"#C2410C"}}/>
            <span className="bc-cpop-status" style={{color: c.status==="Pending"?"#7a6800":"#C2410C"}}>
              {c.status==="Pending" ? `Awaiting review · waiting ${ageLabel}` : "Rejected"}
            </span>
          </div>
          <div className="bc-cpop-id">{c.id}</div>
        </div>
      </div>

      {/* Appeal callout */}
      {c.appealMessage && (
        <div style={{margin:"4px 0 12px",padding:"12px 14px",borderRadius:12,background:"color-mix(in srgb,#5BA5C9 10%,transparent)",border:"1px solid color-mix(in srgb,#5BA5C9 35%,transparent)"}}>
          <div style={{fontSize:12,fontWeight:700,color:"#2E6F8E",marginBottom:4}}>💬 Chef's appeal</div>
          <div style={{fontSize:13.5,color:"var(--c-ink)",lineHeight:1.5}}>{c.appealMessage}</div>
        </div>
      )}

      {/* Previous rejection reason */}
      {c.status==="Rejected" && c.rejectionReason && (
        <div className="bc-cpop-row" style={{borderRadius:10,marginTop:8}}>
          <span>Rejection reason</span><b style={{maxWidth:"60%"}}>{c.rejectionReason}</b>
        </div>
      )}

      {/* Details */}
      <div className="bc-cpop-body">
        {rows.length>0 ? (
          <div className="bc-cpop-dl">
            {rows.map((r,i)=>(<div key={i} className="bc-cpop-dl-row"><dt>{r.label}</dt><dd>{r.value}</dd></div>))}
          </div>
        ) : <p className="bc-cpop-empty">No details submitted.</p>}
        {c.bio && <p className="bc-cpop-bio">{c.bio}</p>}
        {(c.categories||[]).length>0 && (
          <div className="bc-cpop-cats">
            <p className="bc-cpop-cats-label">Categories</p>
            <div className="bc-detail-tags">{c.categories.map(d=><Tag key={d}>{d}</Tag>)}</div>
          </div>
        )}
      </div>

      {/* Actions */}
      {canReview ? (
        <div className="bc-cpop-actions">
          <button className="bc-cpop-btn bc-cpop-btn--activate" onClick={onApprove}>
            <Icon name="check" size={17}/><span>{c.status==="Rejected"?"Approve anyway":"Approve & activate"}</span>
          </button>
          {c.status!=="Rejected" && (
            <button className="bc-cpop-btn bc-cpop-btn--remove" onClick={onReject}>
              <Icon name="x" size={17}/><span>Reject</span>
            </button>
          )}
        </div>
      ) : (
        <div className="bc-cpop-empty" style={{marginTop:12}}>View only — your role can't review applications.</div>
      )}
    </div>
  );
}

function RejectForm({ chef, onCancel, onConfirm }) {
  const [reason, setReason] = useS("");
  const presets = ["Incomplete kitchen photos","Missing/invalid National ID","Kitchen doesn't meet hygiene standards","Outside our service areas","Duplicate application"];
  return (
    <div className="bc-compose-form">
      <p style={{fontSize:13.5,color:"var(--c-ink-2)",margin:0}}>
        This reason is shown to <b>{chef.name}</b> in the app, where they can fix their details and reapply or appeal.
      </p>
      <div className="bc-cat-chips">
        {presets.map(p=>(
          <button type="button" key={p} className={"bc-cat-chip"+(reason===p?" is-on":"")} onClick={()=>setReason(p)}>{p}</button>
        ))}
      </div>
      <label className="bc-field">
        <span className="bc-field-label">Reason</span>
        <textarea className="bc-textarea" rows={3} value={reason} onChange={e=>setReason(e.target.value)}
          placeholder="Explain why, so the chef knows what to fix…"/>
      </label>
      <div className="bc-compose-actions">
        <button type="button" className="bc-btn" onClick={onCancel}>Cancel</button>
        <button type="button" className="bc-btn bc-btn--danger" disabled={!reason.trim()} onClick={()=>onConfirm(reason.trim())}>
          <Icon name="x" size={15}/>Reject application
        </button>
      </div>
    </div>
  );
}

Object.assign(window, {
  OverviewView, ChefsView, OrdersView, CustomersView,
  OpsView, ControlsView, NotificationsView, CRMView,
  ApplicationsView,
});
