// shared.jsx — SideNav, TopBar, common bits, fake data, locale strings

const t = (lang) => ({
  ar: {
    dashboard: "لوحة التحكم", accounts: "الحسابات الإعلانية", alerts: "تنبيهات المديونيات",
    notifs: "قنوات الإشعارات", report: "بناء التقرير", schedule: "جدولة التقارير", account: "تفاصيل الحساب",
    landing: "الرئيسية", onboard: "ربط الحسابات", settings: "الإعدادات",
    work: "العمليات", setup: "الإعداد",
    today: "اليوم", yesterday: "أمس", last7: "آخر ٧ أيام", last30: "آخر ٣٠ يوم",
    spend: "المصروف", sales: "قيمة المبيعات", orders: "عدد الطلبات", roas: "ROAS", cpa: "تكلفة الطلب",
    search: "ابحث في الحسابات والحملات…", new: "جديد",
    saveAll: "حفظ الكل", connect: "ربط حساب", payNow: "ادفع الآن", view: "عرض",
    accountsTotal: "إجمالي الحسابات", suspended: "حسابات موقوفة", debt: "إجمالي المديونيات", activeAds: "إعلانات نشطة",
    arabicReport: "تقرير عربي يومي مخصص",
    sendVia: "أرسل عبر",
    you: "محمد العمري", role: "Performance Lead",
  },
  en: {
    dashboard: "Dashboard", accounts: "Ad Accounts", alerts: "Debt alerts",
    notifs: "Notification channels", report: "Report builder", schedule: "Report schedule", account: "Account detail",
    landing: "Home", onboard: "Connect accounts", settings: "Settings",
    work: "Operations", setup: "Setup",
    today: "Today", yesterday: "Yesterday", last7: "Last 7 days", last30: "Last 30 days",
    spend: "Spend", sales: "Sales value", orders: "Orders", roas: "ROAS", cpa: "Cost / order",
    search: "Search accounts and campaigns…", new: "New",
    saveAll: "Save all", connect: "Connect account", payNow: "Pay now", view: "View",
    accountsTotal: "Total accounts", suspended: "Suspended", debt: "Outstanding debt", activeAds: "Active ads",
    arabicReport: "Custom daily Arabic report",
    sendVia: "Send via",
    you: "Mohamed Al-Omari", role: "Performance Lead",
  },
}[lang]);

window.useT = (lang) => t(lang);

// ─── Side navigation ─────────────────────────────────────────────────
function SideNav({ route, setRoute, lang }) {
  const L = t(lang);
  const items = [
    { group: L.work, links: [
      { id: "dashboard", label: L.dashboard, icon: "home" },
      { id: "accounts",  label: L.accounts,  icon: "grid" },
      { id: "alerts",    label: L.alerts,    icon: "alert", badge: 3 },
      { id: "account",   label: L.account,   icon: "card", indent: true },
    ]},
    { group: L.setup, links: [
      { id: "onboard",  label: L.onboard,  icon: "link" },
      { id: "report",   label: L.report,   icon: "doc" },
      { id: "schedule", label: L.schedule, icon: "cal" },
      { id: "notifs",   label: L.notifs,   icon: "bell" },
    ]},
  ];
  return (
    <nav className="sidenav">
      <div className="brand">
        <div className="brand-mark">R</div>
        <div className="brand-name">
          <b>{lang === "ar" ? "روّج برو" : "Rawj Pro"}</b>
          <span>rawj.pro</span>
        </div>
      </div>
      <button className="nav-item" onClick={() => setRoute("landing")} aria-current={route === "landing" ? "page" : null}>
        <Icon.home />
        <span>{L.landing}</span>
      </button>
      {items.map((g) => (
        <React.Fragment key={g.group}>
          <div className="nav-group">{g.group}</div>
          {g.links.map((l) => {
            const Ic = Icon[l.icon];
            return (
              <button key={l.id} className="nav-item" aria-current={route === l.id ? "page" : null}
                      onClick={() => setRoute(l.id)} style={l.indent ? { paddingInlineStart: 28, fontSize: 12.5, color: "var(--muted)" } : null}>
                <Ic />
                <span>{l.label}</span>
                {l.badge ? <span className="badge-pill">{l.badge}</span> : null}
              </button>
            );
          })}
        </React.Fragment>
      ))}
      <div className="user-card">
        <div className="avatar">MO</div>
        <div style={{ minWidth: 0 }}>
          <div className="who">{L.you}</div>
          <div className="role">{L.role}</div>
        </div>
      </div>
    </nav>
  );
}

// ─── Top bar ─────────────────────────────────────────────────────────
function TopBar({ crumb, title, lang, setLang, right }) {
  const L = t(lang);
  return (
    <header className="topbar">
      <div>
        {crumb ? <div className="crumb">{crumb}</div> : null}
        <h1>{title}</h1>
      </div>
      <div className="topbar-actions">
        <div className="search">
          <Icon.search size={14} />
          <input placeholder={L.search} />
          <kbd>⌘K</kbd>
        </div>
        <div className="seg" role="tablist" aria-label="language">
          <button aria-pressed={lang === "ar"} onClick={() => setLang("ar")} style={{ fontFamily: "var(--font-ar)" }}>عربي</button>
          <button aria-pressed={lang === "en"} onClick={() => setLang("en")} style={{ fontFamily: "var(--font-ltn)" }}>EN</button>
        </div>
        {right}
      </div>
    </header>
  );
}

// ─── Tiny chart helpers ──────────────────────────────────────────────
function Spark({ data, height = 36, stroke = "var(--primary)", fill = true }) {
  const w = 120, h = height, pad = 2;
  const max = Math.max(...data), min = Math.min(...data);
  const span = max - min || 1;
  const pts = data.map((v, i) => [pad + (i * (w - pad * 2)) / (data.length - 1), h - pad - ((v - min) / span) * (h - pad * 2)]);
  const d = pts.map((p, i) => `${i ? "L" : "M"}${p[0].toFixed(1)} ${p[1].toFixed(1)}`).join(" ");
  const area = `${d} L${pts[pts.length - 1][0]} ${h - pad} L${pts[0][0]} ${h - pad} Z`;
  return (
    <svg viewBox={`0 0 ${w} ${h}`} className="spark" preserveAspectRatio="none">
      {fill && <path d={area} fill={stroke} opacity=".12" />}
      <path d={d} fill="none" stroke={stroke} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function BarChart({ data, height = 130, color = "var(--primary)", labels = [] }) {
  const w = 100; const h = 100;
  const max = Math.max(...data, 1);
  return (
    <svg viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" style={{ width: "100%", height, display: "block" }}>
      {data.map((v, i) => {
        const bw = (w - 2) / data.length - 1.2;
        const bh = (v / max) * (h - 14);
        const x = 1 + i * (bw + 1.2);
        const y = h - 12 - bh;
        return (
          <g key={i}>
            <rect x={x} y={2} width={bw} height={h - 14} fill="var(--line)" rx=".8" />
            <rect x={x} y={y} width={bw} height={bh} fill={color} rx=".8" />
            {labels[i] ? <text x={x + bw / 2} y={h - 3} textAnchor="middle" fontSize="3.6" fill="var(--muted)" fontFamily="var(--font-mono)">{labels[i]}</text> : null}
          </g>
        );
      })}
    </svg>
  );
}

function AreaChart({ series, height = 220 }) {
  const w = 600; const h = 200;
  const padL = 30, padB = 22, padT = 8, padR = 8;
  const max = Math.max(...series.flatMap(s => s.data));
  const n = series[0].data.length;
  const xAt = (i) => padL + (i * (w - padL - padR)) / (n - 1);
  const yAt = (v) => padT + (h - padT - padB) - (v / max) * (h - padT - padB);
  const days = ["س","ح","ن","ث","ر","خ","ج"];
  const fmtAxis = (v) => v >= 1000 ? `${Math.round(v / 1000)}k` : `${Math.round(v)}`;
  return (
    <svg viewBox={`0 0 ${w} ${h}`} style={{ width: "100%", height, display: "block" }}>
      {[0, 0.25, 0.5, 0.75, 1].map((p, i) => (
        <g key={i}>
          <line x1={padL} x2={w - padR} y1={padT + p * (h - padT - padB)} y2={padT + p * (h - padT - padB)} stroke="var(--line)" />
          <text x={padL - 6} y={padT + p * (h - padT - padB) + 3} textAnchor="end" fontSize="9" fill="var(--muted)" fontFamily="var(--font-mono)">
            {fmtAxis(max * (1 - p))}
          </text>
        </g>
      ))}
      {series[0].data.map((_, i) => (
        <text key={i} x={xAt(i)} y={h - 6} textAnchor="middle" fontSize="9" fill="var(--muted)" fontFamily="var(--font-mono)">{days[i] || `D${i+1}`}</text>
      ))}
      {series.map((s, si) => {
        const d = s.data.map((v, i) => `${i ? "L" : "M"}${xAt(i)} ${yAt(v)}`).join(" ");
        const area = `${d} L${xAt(n - 1)} ${h - padB} L${xAt(0)} ${h - padB} Z`;
        return (
          <g key={si}>
            <path d={area} fill={s.color} opacity={si === 0 ? .14 : .06} />
            <path d={d} fill="none" stroke={s.color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
            {s.data.map((v, i) => (
              <circle key={i} cx={xAt(i)} cy={yAt(v)} r="2.5" fill="var(--surface)" stroke={s.color} strokeWidth="1.5" />
            ))}
          </g>
        );
      })}
    </svg>
  );
}

// ─── Platform mark ───────────────────────────────────────────────────
function Plat({ kind, size = 22 }) {
  const labels = { meta: "f", google: "G", tiktok: "♪", snap: "👻" };
  return <span className={`plat plat-${kind}`} style={{ width: size, height: size, fontSize: size * 0.5 }}>
    {kind === "snap" ? <svg width="14" height="14" viewBox="0 0 24 24" fill="#000"><path d="M12 2c3 0 5 2 5 5v3c1 0 2 1 2 1s-1 2-2 3l3 3c-2 1-4 1-5 1l-1 2-2-1-2 1-1-2c-1 0-3 0-5-1l3-3c-1-1-2-3-2-3s1-1 2-1V7c0-3 2-5 5-5z"/></svg> : labels[kind]}
  </span>;
}

// ─── Fake data ───────────────────────────────────────────────────────
const ACCOUNTS = [
  { id: "act-001", name: "Zalma — Main Catalog", platform: "meta", spend: 14820, sales: 47210, orders: 386, roas: 3.18, status: "active",  spark: [22,18,25,28,24,29,32], currency: "EGP" },
  { id: "act-002", name: "Zalma — Retargeting",   platform: "meta", spend: 6210,  sales: 18940, orders: 142, roas: 3.05, status: "active",  spark: [12,14,15,11,13,16,15], currency: "EGP" },
  { id: "act-003", name: "Zalma Brand Search",    platform: "google", spend: 9410, sales: 21300, orders: 168, roas: 2.26, status: "debt", debt: 1240, spark: [20,22,18,24,26,23,21], currency: "USD" },
  { id: "act-004", name: "Zalma KSA — TikTok",    platform: "tiktok", spend: 11200, sales: 33800, orders: 254, roas: 3.02, status: "active", spark: [30,32,28,35,38,36,40], currency: "SAR" },
  { id: "act-005", name: "Zalma Snap Stories",    platform: "snap",   spend: 4180,  sales: 9210, orders: 88, roas: 2.20, status: "suspended", debt: 820, spark: [9,11,13,12,10,8,6], currency: "USD" },
  { id: "act-006", name: "Zalma — Performance",   platform: "google", spend: 22440, sales: 71820, orders: 612, roas: 3.20, status: "active", spark: [42,46,49,51,55,58,60], currency: "EGP" },
];

const fmt = (n, c = "EGP") => new Intl.NumberFormat("en-US", { style: "currency", currency: c, maximumFractionDigits: 0 }).format(n);
const fmtN = (n) => new Intl.NumberFormat("en-US").format(n);

window.SideNav = SideNav;
window.TopBar = TopBar;
window.Spark = Spark;
window.BarChart = BarChart;
window.AreaChart = AreaChart;
window.Plat = Plat;
window.ACCOUNTS = ACCOUNTS;
window.fmt = fmt; window.fmtN = fmtN;
