// Admin screens (desktop, inside browser frame)
// Shell: sidebar nav + top header + content area
// Screens: dashboard, daftar, detail, baru, pengaturan

const { useState: useS, useMemo: useM } = React;

// ═══════════════════════════════════════════════════════
// SHELL — Sidebar + Top header
// ═══════════════════════════════════════════════════════
function AdminShell({ activeScreen, navigate, theme, children, pageTitle }) {
  const menu = [
    { id: "admin-dashboard", name: "Dashboard",      icon: "dashboard"     },
    { id: "admin-baru",      name: "Pesanan Baru",   icon: "add_circle"    },
    { id: "admin-daftar",    name: "Daftar Pesanan", icon: "receipt_long"  },
    { id: "admin-pengaturan",name: "Pengaturan",     icon: "settings"      },
  ];

  return (
    <div className="ad-shell">
      <aside className="ad-sidebar">
        <div className="ad-side-head">
          <div className="ad-side-logo"><img src="assets/logo.png" alt="" /></div>
          <h2>Damelkeun</h2>
        </div>
        <nav className="ad-nav">
          {menu.map((m) => {
            const isActive = activeScreen === m.id || (m.id === "admin-daftar" && activeScreen === "admin-detail");
            return (
              <button key={m.id} className={`ad-nav-item ${isActive ? "active" : ""}`} onClick={() => navigate(m.id)}
                style={isActive ? { background: `${theme.primary}1a`, color: theme.primary } : {}}>
                <MI name={m.icon} size={18} />
                <span>{m.name}</span>
              </button>
            );
          })}
        </nav>
        <div className="ad-side-foot">
          <button className="ad-logout">
            <MI name="logout" size={18} />
            <span>Keluar</span>
          </button>
        </div>
      </aside>

      <div className="ad-main">
        <header className="ad-top">
          <h2 className="ad-page-title">{pageTitle}</h2>
          <div className="ad-profile">
            <div className="ad-avatar" style={{ background: `linear-gradient(135deg, ${theme.primary}, ${theme.secondary})` }}>A</div>
            <div className="ad-prof-info">
              <p>Admin Utama</p>
              <p className="ad-role" style={{ color: theme.primary }}>
                <MI name="verified" size={11} />
                Administrator
              </p>
            </div>
          </div>
        </header>
        <main className="ad-content">{children}</main>
      </div>

      <style>{`
        .ad-shell { display: flex; height: 100%; background: #f2f3f6; font-family: "Inter", system-ui, sans-serif; color: #1d1e20; }
        .ad-sidebar { width: 240px; background: white; border-right: 1px solid #e5e7eb; display: flex; flex-direction: column; flex-shrink: 0; }
        .ad-side-head { height: 64px; display: flex; align-items: center; padding: 0 16px; gap: 10px; border-bottom: 1px solid #f3f4f6; }
        .ad-side-logo { width: 32px; height: 32px; padding: 3px; }
        .ad-side-logo img { width: 100%; height: 100%; object-fit: contain; }
        .ad-side-head h2 { font-size: 1rem; font-weight: 800; letter-spacing: -0.3px; }
        .ad-nav { flex: 1; padding: 16px 12px; display: flex; flex-direction: column; gap: 2px; }
        .ad-nav-item {
          display: flex; align-items: center; gap: 10px;
          padding: 10px 12px; border-radius: 10px;
          color: #6b7280; font-weight: 500; font-size: 0.85rem;
          background: transparent; border: none; cursor: pointer;
          text-align: left; transition: all 0.15s;
        }
        .ad-nav-item:hover { background: #f9fafb; color: #111827; }
        .ad-nav-item.active { font-weight: 700; }
        .ad-side-foot { padding: 12px; border-top: 1px solid #f3f4f6; }
        .ad-logout {
          display: flex; align-items: center; gap: 10px;
          width: 100%; padding: 10px 12px; border-radius: 10px;
          color: #ef4444; font-weight: 600; font-size: 0.85rem;
          background: transparent; border: none; cursor: pointer; text-align: left;
        }
        .ad-logout:hover { background: #fef2f2; }

        .ad-main { flex: 1; min-width: 0; display: flex; flex-direction: column; overflow: hidden; }
        .ad-top {
          height: 64px; background: white; border-bottom: 1px solid #e5e7eb;
          display: flex; align-items: center; justify-content: space-between;
          padding: 0 24px; flex-shrink: 0;
        }
        .ad-page-title { font-size: 1.05rem; font-weight: 800; }
        .ad-profile { display: flex; align-items: center; gap: 10px; }
        .ad-avatar {
          width: 36px; height: 36px; border-radius: 50%;
          display: flex; align-items: center; justify-content: center;
          color: white; font-weight: 800; font-size: 0.9rem;
        }
        .ad-prof-info p:first-child { font-size: 0.82rem; font-weight: 800; }
        .ad-role { display: inline-flex; align-items: center; gap: 3px; font-size: 0.66rem; font-weight: 700; margin-top: 1px; }

        .ad-content { flex: 1; padding: 20px 24px; overflow-y: auto; }

        /* Reusable card */
        .ad-card { background: white; border-radius: 14px; padding: 18px; box-shadow: 0 4px 20px rgba(0,0,0,0.04); }
        .ad-card.dashed { border-top: 2px dashed ${theme.primary}; }

        .ad-section-title { font-size: 0.85rem; font-weight: 800; margin-bottom: 14px; display: flex; align-items: center; gap: 6px; }
        .ad-section-title .material-symbols-outlined { color: ${theme.primary}; font-size: 1rem !important; }
      `}</style>
    </div>
  );
}

// ═══════════════════════════════════════════════════════
// 1) DASHBOARD
// ═══════════════════════════════════════════════════════
function AdminDashboard({ navigate, theme }) {
  const stats = [
    { label: "Order Aktif",        value: 6, icon: "inventory_2", color: theme.primary,    bg: `${theme.primary}1a` },
    { label: "Sedang Diproses",    value: 5, icon: "hourglass_empty", color: theme.secondary, bg: `${theme.secondary}1a` },
    { label: "Selesai Bulan Ini",  value: 12, icon: "check_circle", color: "#10b981",       bg: "#d1fae5" },
    { label: "Perlu Perhatian",    value: 1, icon: "warning",      color: "#ef4444",       bg: "#fef2f2" },
  ];

  const chartData = [
    { name: "DP",            value: 0 },
    { name: "Belanja Kain",  value: 1 },
    { name: "Potong Kain",   value: 1 },
    { name: "Sablon/Bordir", value: 1 },
    { name: "Jahit",         value: 1 },
    { name: "QC",            value: 1 },
    { name: "Packing",       value: 0 },
    { name: "Pengiriman",    value: 1 },
  ];
  const maxV = Math.max(...chartData.map((d) => d.value), 1);

  return (
    <div className="dash">
      {/* Welcome row */}
      <div className="ad-card dashed dash-welcome">
        <div>
          <h1>Selamat datang, Admin 👋</h1>
          <p>Gambaran umum produksi garmen hari ini.</p>
        </div>
        <button className="dash-cta" onClick={() => navigate("admin-baru")}
          style={{ background: `linear-gradient(135deg, ${theme.primary}, ${theme.secondary})`, boxShadow: `0 8px 20px ${theme.primary}45` }}>
          <MI name="add" size={18} /> Pesanan Baru
        </button>
      </div>

      {/* Stats */}
      <div className="dash-stats">
        {stats.map((s) => (
          <div key={s.label} className="ad-card stat">
            <div>
              <p className="stat-label">{s.label}</p>
              <h3 className="stat-value">{s.value}</h3>
            </div>
            <div className="stat-ic" style={{ background: s.bg, color: s.color }}>
              <MI name={s.icon} size={20} />
            </div>
          </div>
        ))}
      </div>

      {/* Chart + Recent orders */}
      <div className="dash-grid">
        <div className="ad-card dashed">
          <h2 className="ad-section-title"><MI name="bar_chart" size={16} />Distribusi Tahapan</h2>
          <p className="dash-chart-sub">Order aktif per tahap produksi</p>
          <div className="dash-chart">
            {chartData.map((d) => (
              <div key={d.name} className="dash-bar-row">
                <span className="dash-bar-label">{d.name}</span>
                <div className="dash-bar-track">
                  <div className="dash-bar-fill" style={{
                    width: `${(d.value/maxV)*100}%`,
                    background: `linear-gradient(90deg, ${theme.primary}, ${theme.secondary})`,
                  }} />
                </div>
                <span className="dash-bar-val">{d.value}</span>
              </div>
            ))}
          </div>
        </div>

        <div className="ad-card dashed">
          <div className="dash-recent-head">
            <h2 className="ad-section-title"><MI name="receipt_long" size={16} />Pesanan Terbaru</h2>
            <button className="dash-link" onClick={() => navigate("admin-daftar")}
              style={{ borderColor: theme.primary, color: theme.primary }}>
              Lihat Semua <MI name="arrow_forward" size={14} />
            </button>
          </div>
          <table className="dash-table">
            <thead>
              <tr>
                {["Order ID", "Pembeli", "Tahap", "Progress", "Status"].map((h) => <th key={h}>{h}</th>)}
              </tr>
            </thead>
            <tbody>
              {ADMIN_ORDERS.slice(0, 6).map((o) => {
                const isDone = o.status === "Done";
                const isCancel = o.status === "Cancel";
                const badge = isDone
                  ? { label: "Selesai",    bg: "#d1fae5", color: "#15803d" }
                  : isCancel
                  ? { label: "Dibatalkan", bg: "#fee2e2", color: "#dc2626" }
                  : o.overall_persen === 0
                  ? { label: "Menunggu",   bg: "#f2f3f6", color: "#727586" }
                  : { label: "Diproses",   bg: "#fef9ec", color: "#d97706" };
                return (
                  <tr key={o.order_id} onClick={() => navigate("admin-detail", o.order_id)}>
                    <td className="td-id">{o.order_id}</td>
                    <td>{o.nama_pembeli}</td>
                    <td className="td-stage">{o.current_stage}</td>
                    <td>
                      <div className="td-progress">
                        <div className="td-bar"><div style={{
                          width: `${o.overall_persen}%`,
                          background: isDone ? theme.primary : `linear-gradient(90deg, ${theme.primary}, ${theme.secondary})`,
                        }} /></div>
                        <span>{o.overall_persen}%</span>
                      </div>
                    </td>
                    <td>
                      <span className="td-badge" style={{ background: badge.bg, color: badge.color }}>{badge.label}</span>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </div>

      <style>{`
        .dash { display: flex; flex-direction: column; gap: 16px; }
        .dash-welcome { display: flex; align-items: center; justify-content: space-between; gap: 16px; }
        .dash-welcome h1 { font-size: 1.4rem; font-weight: 800; letter-spacing: -0.5px; }
        .dash-welcome p { font-size: 0.82rem; color: #727586; margin-top: 2px; }
        .dash-cta {
          padding: 10px 16px; color: white; border: none; border-radius: 10px;
          font-weight: 800; font-size: 0.85rem; cursor: pointer;
          display: inline-flex; align-items: center; gap: 6px;
        }
        .dash-stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: 14px; }
        .stat { display: flex; justify-content: space-between; align-items: flex-start; border-top: 2px dashed ${theme.primary}; }
        .stat-label { font-size: 0.7rem; color: #727586; font-weight: 700; text-transform: uppercase; letter-spacing: 0.4px; margin-bottom: 6px; }
        .stat-value { font-size: 1.9rem; font-weight: 800; line-height: 1; }
        .stat-ic { width: 42px; height: 42px; border-radius: 10px; display: flex; align-items: center; justify-content: center; }

        .dash-grid { display: grid; grid-template-columns: 320px 1fr; gap: 14px; }
        .dash-chart-sub { font-size: 0.72rem; color: #727586; margin-bottom: 12px; margin-top: -8px; }
        .dash-chart { display: flex; flex-direction: column; gap: 8px; }
        .dash-bar-row { display: grid; grid-template-columns: 100px 1fr 28px; gap: 8px; align-items: center; font-size: 0.74rem; }
        .dash-bar-label { color: #475569; font-weight: 600; }
        .dash-bar-track { height: 8px; background: #f0f0f0; border-radius: 999px; overflow: hidden; }
        .dash-bar-fill { height: 100%; border-radius: 999px; transition: width 0.6s; }
        .dash-bar-val { font-weight: 800; color: #1d1e20; text-align: right; font-family: monospace; }

        .dash-recent-head { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; }
        .dash-recent-head .ad-section-title { margin-bottom: 0; }
        .dash-link {
          display: inline-flex; align-items: center; gap: 3px;
          padding: 4px 10px; border: 1.5px solid; border-radius: 8px;
          background: transparent; font-weight: 800; font-size: 0.72rem; cursor: pointer;
        }

        .dash-table { width: 100%; border-collapse: collapse; font-size: 0.78rem; }
        .dash-table th {
          text-align: left; padding: 6px 8px; font-size: 0.66rem; font-weight: 800;
          color: #9ca3af; text-transform: uppercase; letter-spacing: 0.5px;
          border-bottom: 2px solid #f0f0f0;
        }
        .dash-table td { padding: 9px 8px; border-bottom: 1px solid #f9fafb; }
        .dash-table tbody tr { cursor: pointer; transition: background 0.15s; }
        .dash-table tbody tr:hover { background: #f9fafb; }
        .td-id { font-family: monospace; font-weight: 800; color: ${theme.primary}; }
        .td-stage { color: #475569; }
        .td-progress { display: flex; align-items: center; gap: 6px; min-width: 100px; }
        .td-bar { flex: 1; height: 5px; background: #f0f0f0; border-radius: 999px; overflow: hidden; }
        .td-bar > div { height: 100%; }
        .td-progress > span { font-size: 0.7rem; font-weight: 800; color: #475569; min-width: 28px; font-family: monospace; }
        .td-badge { padding: 2px 8px; border-radius: 999px; font-size: 0.66rem; font-weight: 800; white-space: nowrap; }
      `}</style>
    </div>
  );
}

// ═══════════════════════════════════════════════════════
// 2) DAFTAR PESANAN
// ═══════════════════════════════════════════════════════
function AdminDaftar({ navigate, theme }) {
  const [filter, setFilter] = useS("all");
  const [search, setSearch] = useS("");

  const filtered = useM(() => {
    return ADMIN_ORDERS.filter((o) => {
      if (filter === "active" && o.status !== "Active") return false;
      if (filter === "done"   && o.status !== "Done")   return false;
      if (filter === "cancel" && o.status !== "Cancel") return false;
      if (search && !`${o.order_id} ${o.nama_pembeli} ${o.detail_produk}`.toLowerCase().includes(search.toLowerCase())) return false;
      return true;
    });
  }, [filter, search]);

  const counts = {
    all:    ADMIN_ORDERS.length,
    active: ADMIN_ORDERS.filter((o) => o.status === "Active").length,
    done:   ADMIN_ORDERS.filter((o) => o.status === "Done").length,
    cancel: ADMIN_ORDERS.filter((o) => o.status === "Cancel").length,
  };

  return (
    <div className="df">
      <div className="ad-card dashed">
        {/* Toolbar */}
        <div className="df-toolbar">
          <div className="df-search">
            <MI name="search" size={18} style={{ opacity: 0.5 }} />
            <input value={search} onChange={(e) => setSearch(e.target.value)} placeholder="Cari order ID, nama, produk..." />
          </div>
          <div className="df-tabs">
            {[
              { id: "all",    label: "Semua" },
              { id: "active", label: "Aktif" },
              { id: "done",   label: "Selesai" },
              { id: "cancel", label: "Cancel" },
            ].map((t) => (
              <button key={t.id} className={`df-tab ${filter === t.id ? "active" : ""}`}
                onClick={() => setFilter(t.id)}
                style={filter === t.id ? { background: theme.primary, color: "white" } : {}}>
                {t.label} <span className="df-tab-count">{counts[t.id]}</span>
              </button>
            ))}
          </div>
        </div>

        <table className="dash-table df-table">
          <thead>
            <tr>
              {["Order ID", "Pembeli", "Produk", "Qty", "Tanggal", "Tahap", "Progress", "Status", ""].map((h) => <th key={h}>{h}</th>)}
            </tr>
          </thead>
          <tbody>
            {filtered.map((o) => {
              const isDone = o.status === "Done";
              const isCancel = o.status === "Cancel";
              const badge = isDone
                ? { label: "Selesai",    bg: "#d1fae5", color: "#15803d" }
                : isCancel
                ? { label: "Dibatalkan", bg: "#fee2e2", color: "#dc2626" }
                : o.overall_persen === 0
                ? { label: "Menunggu",   bg: "#f2f3f6", color: "#727586" }
                : { label: "Diproses",   bg: "#fef9ec", color: "#d97706" };
              return (
                <tr key={o.order_id} onClick={() => navigate("admin-detail", o.order_id)}>
                  <td className="td-id">{o.order_id}</td>
                  <td><strong>{o.nama_pembeli}</strong></td>
                  <td className="td-product">{o.detail_produk}</td>
                  <td>{o.qty}</td>
                  <td>{o.tanggal_order}</td>
                  <td className="td-stage">{o.current_stage}</td>
                  <td>
                    <div className="td-progress">
                      <div className="td-bar"><div style={{
                        width: `${o.overall_persen}%`,
                        background: isDone ? theme.primary : `linear-gradient(90deg, ${theme.primary}, ${theme.secondary})`,
                      }} /></div>
                      <span>{o.overall_persen}%</span>
                    </div>
                  </td>
                  <td><span className="td-badge" style={{ background: badge.bg, color: badge.color }}>{badge.label}</span></td>
                  <td><MI name="arrow_forward" size={16} style={{ opacity: 0.4 }} /></td>
                </tr>
              );
            })}
          </tbody>
        </table>

        {filtered.length === 0 && (
          <div className="df-empty">
            <MI name="search_off" size={36} style={{ opacity: 0.3 }} />
            <p>Tidak ada pesanan yang cocok</p>
          </div>
        )}
      </div>

      <style>{`
        .df-toolbar { display: flex; gap: 12px; justify-content: space-between; align-items: center; margin-bottom: 14px; flex-wrap: wrap; }
        .df-search {
          display: flex; align-items: center; gap: 8px;
          padding: 8px 12px; background: #f9fafb; border: 1px solid #e5e7eb;
          border-radius: 10px; flex: 1; min-width: 280px; max-width: 380px;
        }
        .df-search input {
          flex: 1; border: none; background: transparent; outline: none;
          font-size: 0.85rem; color: #1d1e20;
        }
        .df-tabs { display: flex; gap: 4px; background: #f2f3f6; padding: 3px; border-radius: 10px; }
        .df-tab {
          padding: 6px 12px; border-radius: 8px; border: none; background: transparent;
          font-size: 0.78rem; font-weight: 700; color: #6b7280; cursor: pointer;
          display: inline-flex; align-items: center; gap: 5px;
          transition: all 0.15s;
        }
        .df-tab:hover:not(.active) { color: #1d1e20; }
        .df-tab-count {
          background: rgba(0,0,0,0.08); color: inherit;
          padding: 1px 6px; border-radius: 5px;
          font-size: 0.66rem; font-weight: 800; font-family: monospace;
        }
        .df-tab.active .df-tab-count { background: rgba(255,255,255,0.25); color: white; }
        .df-table .td-product { color: #475569; max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
        .df-empty {
          padding: 60px 20px; text-align: center; color: #94a3b8;
          display: flex; flex-direction: column; align-items: center; gap: 10px;
        }
      `}</style>
    </div>
  );
}

// ═══════════════════════════════════════════════════════
// 3) ORDER DETAIL — update progress per stage
// ═══════════════════════════════════════════════════════
function AdminDetail({ navigate, theme, orderId }) {
  const baseOrder = useM(() => {
    return ADMIN_ORDERS.find((o) => o.order_id === orderId) || ADMIN_ORDERS[0];
  }, [orderId]);

  // Stage values — editable
  const [stages, setStages] = useS({
    dp: 100, belanja_kain: 100, potong_kain: 100, sablon_bordir: 100,
    jahit: 70, qc: 0, packing: 0, pengiriman: 0,
  });
  const [notif, setNotif] = useS(null);

  const overall = calcOverall(stages);

  const update = (key, val) => {
    setStages((p) => ({ ...p, [key]: val }));
  };

  const save = () => {
    setNotif("Progress disimpan. WhatsApp notif terkirim ke customer.");
    setTimeout(() => setNotif(null), 3000);
  };

  return (
    <div className="det">
      {/* Back row */}
      <button className="det-back" onClick={() => navigate("admin-daftar")}>
        <MI name="arrow_back" size={16} /> Kembali ke daftar
      </button>

      {/* Order header */}
      <div className="ad-card dashed det-header">
        <div>
          <span className="det-pill" style={{ background: `${theme.primary}1a`, color: theme.primary }}>
            <MI name="receipt" size={14} /> {baseOrder.order_id}
          </span>
          <h1>{baseOrder.nama_pembeli}</h1>
          <p className="det-product">{baseOrder.detail_produk} · <strong>{baseOrder.qty} pcs</strong></p>
        </div>
        <div className="det-overall">
          <div className="det-ring">
            <svg viewBox="0 0 100 100">
              <circle cx="50" cy="50" r="42" fill="none" stroke="#e2e8f0" strokeWidth="8" />
              <circle cx="50" cy="50" r="42" fill="none" stroke={theme.primary} strokeWidth="8" strokeLinecap="round"
                strokeDasharray={`${(overall/100)*264} 264`}
                transform="rotate(-90 50 50)"
                style={{ transition: "stroke-dasharray 0.4s" }} />
            </svg>
            <span style={{ color: theme.primary }}>{overall}<small>%</small></span>
          </div>
          <p className="det-overall-label">Progress Total</p>
        </div>
      </div>

      {/* Notif */}
      {notif && (
        <div className="det-notif" style={{ background: `${theme.primary}15`, color: theme.primary }}>
          <MI name="check_circle" size={18} />
          {notif}
        </div>
      )}

      <div className="det-grid">
        {/* LEFT: progress editor */}
        <div className="ad-card">
          <h2 className="ad-section-title"><MI name="edit_square" size={16} />Update Progress per Tahap</h2>
          <div className="det-stages">
            {STAGES.map((s) => {
              const v = stages[s.key];
              const done = v === 100;
              return (
                <div key={s.key} className={`det-stage ${done ? "done" : ""}`}>
                  <div className="det-stage-head">
                    <div className="det-stage-ic" style={{
                      background: done ? `${theme.primary}1a` : "#f2f3f6",
                      color: done ? theme.primary : "#94a3b8",
                    }}>
                      <MI name={s.icon} size={18} />
                    </div>
                    <div className="det-stage-info">
                      <p className="det-stage-name">{s.label}</p>
                      <p className="det-stage-desc">{s.desc}</p>
                    </div>
                    <span className="det-stage-val" style={{ color: done ? theme.primary : "#475569" }}>{v}%</span>
                  </div>
                  <div className="det-stage-row">
                    <input type="range" min="0" max="100" step="10" value={v}
                      onChange={(e) => update(s.key, Number(e.target.value))}
                      style={{ accentColor: theme.primary }} />
                    <div className="det-quick">
                      {[0, 50, 100].map((q) => (
                        <button key={q} onClick={() => update(s.key, q)}
                          className={v === q ? "active" : ""}
                          style={v === q ? { background: theme.primary, color: "white", borderColor: theme.primary } : {}}>
                          {q}%
                        </button>
                      ))}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
          <div className="det-actions">
            <button className="det-save" onClick={save}
              style={{ background: `linear-gradient(135deg, ${theme.primary}, ${theme.secondary})`, boxShadow: `0 8px 20px ${theme.primary}45` }}>
              <MI name="save" size={16} /> Simpan & Kirim Notif WA
            </button>
          </div>
        </div>

        {/* RIGHT: side panel */}
        <div className="det-side">
          <div className="ad-card det-meta">
            <h2 className="ad-section-title"><MI name="info" size={16} />Info Pesanan</h2>
            <div className="det-meta-row"><span>Tanggal Order</span><strong>{baseOrder.tanggal_order}</strong></div>
            <div className="det-meta-row"><span>Deadline</span><strong style={{ color: "#d97706" }}>5 Jun 2026</strong></div>
            <div className="det-meta-row"><span>Telepon</span><strong>0812-3456-7890</strong></div>
            <div className="det-meta-row"><span>Total Tagihan</span><strong>Rp 14.400.000</strong></div>
            <button className="det-wa">
              <MI name="chat" size={16} /> Chat via WhatsApp
            </button>
          </div>

          <div className="ad-card det-meta">
            <h2 className="ad-section-title"><MI name="photo_library" size={16} />Upload Foto Bukti</h2>
            <div className="det-photo-grid">
              {Object.keys(PHOTO_PLACEHOLDERS).slice(0, 3).map((k) => {
                const p = PHOTO_PLACEHOLDERS[k];
                return (
                  <div key={k} className="det-photo" style={{
                    background: `linear-gradient(135deg, hsl(${p.hue},65%,55%), hsl(${p.hue+30},65%,45%))`,
                  }}>{p.label}</div>
                );
              })}
              <div className="det-photo-add">
                <MI name="add_a_photo" size={20} />
                Tambah Foto
              </div>
            </div>
          </div>
        </div>
      </div>

      <style>{`
        .det { display: flex; flex-direction: column; gap: 14px; }
        .det-back {
          align-self: flex-start;
          padding: 6px 12px; background: transparent; border: none; cursor: pointer;
          color: #475569; font-size: 0.82rem; font-weight: 600;
          display: inline-flex; align-items: center; gap: 4px;
        }
        .det-back:hover { color: ${theme.primary}; }
        .det-header { display: flex; justify-content: space-between; align-items: center; gap: 20px; }
        .det-pill { display: inline-flex; align-items: center; gap: 4px; padding: 3px 9px; border-radius: 14px; font-family: monospace; font-size: 0.72rem; font-weight: 800; margin-bottom: 6px; }
        .det-header h1 { font-size: 1.4rem; font-weight: 800; letter-spacing: -0.4px; margin-bottom: 4px; }
        .det-product { font-size: 0.85rem; color: #475569; }
        .det-overall { display: flex; flex-direction: column; align-items: center; gap: 6px; }
        .det-ring { position: relative; width: 80px; height: 80px; }
        .det-ring svg { width: 100%; height: 100%; }
        .det-ring span {
          position: absolute; inset: 0; display: flex; align-items: center; justify-content: center;
          font-size: 1.3rem; font-weight: 800; letter-spacing: -1px;
        }
        .det-ring small { font-size: 0.75rem; opacity: 0.6; }
        .det-overall-label { font-size: 0.66rem; font-weight: 800; color: #94a3b8; text-transform: uppercase; letter-spacing: 0.4px; }

        .det-notif {
          padding: 10px 14px; border-radius: 10px;
          display: flex; align-items: center; gap: 6px;
          font-size: 0.85rem; font-weight: 700;
          animation: detSlide 0.3s ease;
        }
        @keyframes detSlide { from { transform: translateY(-6px); opacity: 0; } to { opacity: 1; } }

        .det-grid { display: grid; grid-template-columns: 1fr 320px; gap: 14px; }
        .det-stages { display: flex; flex-direction: column; gap: 10px; }
        .det-stage { padding: 12px; border: 1px solid #f0f0f0; border-radius: 10px; transition: border-color 0.2s; }
        .det-stage.done { border-color: ${theme.primary}33; background: ${theme.primary}06; }
        .det-stage-head { display: flex; align-items: center; gap: 10px; margin-bottom: 8px; }
        .det-stage-ic { width: 36px; height: 36px; border-radius: 10px; display: flex; align-items: center; justify-content: center; flex-shrink: 0; }
        .det-stage-info { flex: 1; }
        .det-stage-name { font-size: 0.85rem; font-weight: 800; }
        .det-stage-desc { font-size: 0.7rem; color: #94a3b8; }
        .det-stage-val { font-size: 0.95rem; font-weight: 800; font-family: monospace; }
        .det-stage-row { display: flex; align-items: center; gap: 10px; padding-left: 46px; }
        .det-stage-row input[type=range] { flex: 1; }
        .det-quick { display: flex; gap: 4px; }
        .det-quick button {
          padding: 3px 8px; border: 1px solid #e5e7eb; background: white; border-radius: 6px;
          font-size: 0.66rem; font-weight: 800; color: #6b7280; cursor: pointer;
          font-family: monospace; transition: all 0.15s;
        }
        .det-quick button:hover { border-color: ${theme.primary}; color: ${theme.primary}; }

        .det-actions { display: flex; justify-content: flex-end; margin-top: 16px; }
        .det-save {
          padding: 11px 18px; color: white; border: none; border-radius: 10px;
          font-weight: 800; font-size: 0.88rem; cursor: pointer;
          display: inline-flex; align-items: center; gap: 6px;
        }

        .det-side { display: flex; flex-direction: column; gap: 14px; }
        .det-meta-row {
          display: flex; justify-content: space-between; align-items: center;
          padding: 8px 0; border-bottom: 1px solid #f3f4f6;
          font-size: 0.82rem; color: #475569;
        }
        .det-meta-row:last-of-type { border-bottom: none; }
        .det-meta-row strong { color: #1d1e20; font-weight: 800; }
        .det-wa {
          margin-top: 8px; width: 100%; padding: 9px;
          background: #25d366; color: white; border: none; border-radius: 10px;
          font-size: 0.82rem; font-weight: 800; cursor: pointer;
          display: inline-flex; align-items: center; justify-content: center; gap: 5px;
        }

        .det-photo-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
        .det-photo {
          aspect-ratio: 1;
          border-radius: 10px;
          padding: 8px;
          display: flex; align-items: flex-end;
          color: white; font-size: 0.66rem; font-weight: 800;
          box-shadow: 0 2px 6px rgba(0,0,0,0.15);
        }
        .det-photo-add {
          aspect-ratio: 1; border: 2px dashed #cbd5e1; border-radius: 10px;
          display: flex; flex-direction: column; align-items: center; justify-content: center;
          gap: 4px; color: #94a3b8; cursor: pointer; font-size: 0.7rem; font-weight: 700;
          transition: all 0.15s;
        }
        .det-photo-add:hover { border-color: ${theme.primary}; color: ${theme.primary}; }
      `}</style>
    </div>
  );
}

// ═══════════════════════════════════════════════════════
// 4) PESANAN BARU — form
// ═══════════════════════════════════════════════════════
function AdminBaru({ navigate, theme }) {
  const [form, setForm] = useS({
    nama: "", hp: "", produk: "", qty: "", deadline: "", catatan: "",
  });
  const [submitted, setSubmitted] = useS(false);

  const update = (k, v) => setForm((p) => ({ ...p, [k]: v }));

  const submit = (e) => {
    e?.preventDefault();
    setSubmitted(true);
    setTimeout(() => {
      setSubmitted(false);
      navigate("admin-dashboard");
    }, 2500);
  };

  if (submitted) {
    return (
      <div className="baru-done">
        <div className="ad-card baru-done-card">
          <div className="baru-check" style={{ background: `${theme.primary}1a`, color: theme.primary }}>
            <MI name="check_circle" size={48} />
          </div>
          <h1>Pesanan Berhasil Dibuat!</h1>
          <p>Order ID <strong style={{ color: theme.primary }}>ORD-260526-002</strong> sudah dibuat. Link tracking dikirim ke WhatsApp customer.</p>
          <div className="baru-spinner-row">
            <div className="baru-spinner" style={{ borderTopColor: theme.primary }} />
            <span>Mengarahkan ke dashboard...</span>
          </div>
        </div>
        <style>{`
          .baru-done { display: flex; align-items: center; justify-content: center; padding: 40px; }
          .baru-done-card { text-align: center; max-width: 460px; padding: 36px 28px; }
          .baru-check { width: 88px; height: 88px; border-radius: 50%; margin: 0 auto 16px; display: flex; align-items: center; justify-content: center; }
          .baru-done-card h1 { font-size: 1.4rem; font-weight: 800; letter-spacing: -0.4px; margin-bottom: 8px; }
          .baru-done-card p { color: #475569; font-size: 0.88rem; line-height: 1.5; margin-bottom: 20px; }
          .baru-spinner-row { display: flex; align-items: center; justify-content: center; gap: 8px; color: #94a3b8; font-size: 0.78rem; }
          .baru-spinner { width: 18px; height: 18px; border: 2.5px solid #e2e8f0; border-radius: 50%; animation: spin 0.8s linear infinite; }
          @keyframes spin { to { transform: rotate(360deg); } }
        `}</style>
      </div>
    );
  }

  return (
    <form className="baru" onSubmit={submit}>
      <div className="ad-card dashed">
        <h2 className="ad-section-title"><MI name="add_circle" size={16} />Detail Customer</h2>
        <div className="baru-row">
          <div className="baru-field">
            <label>Nama Pembeli *</label>
            <input value={form.nama} onChange={(e) => update("nama", e.target.value)} placeholder="cth: Pak Bayu Saputra" required />
          </div>
          <div className="baru-field">
            <label>Nomor WhatsApp *</label>
            <input value={form.hp} onChange={(e) => update("hp", e.target.value)} placeholder="cth: 0812-3456-7890" required />
          </div>
        </div>
      </div>

      <div className="ad-card dashed">
        <h2 className="ad-section-title"><MI name="checkroom" size={16} />Detail Pesanan</h2>
        <div className="baru-field">
          <label>Produk *</label>
          <textarea value={form.produk} onChange={(e) => update("produk", e.target.value)}
            placeholder="cth: Kaos polo lengan pendek custom bordir logo perusahaan, bahan cotton combed 30s, ukuran S–XXL" required />
        </div>
        <div className="baru-row">
          <div className="baru-field">
            <label>Jumlah (pcs) *</label>
            <input type="number" value={form.qty} onChange={(e) => update("qty", e.target.value)} placeholder="cth: 120" required />
          </div>
          <div className="baru-field">
            <label>Deadline *</label>
            <input type="date" value={form.deadline} onChange={(e) => update("deadline", e.target.value)} required />
          </div>
        </div>
        <div className="baru-field">
          <label>Catatan Tambahan</label>
          <textarea value={form.catatan} onChange={(e) => update("catatan", e.target.value)} placeholder="Catatan internal (opsional)" />
        </div>
      </div>

      <div className="ad-card baru-summary" style={{ borderLeft: `4px solid ${theme.primary}` }}>
        <div>
          <p className="baru-sum-label">Setelah disimpan:</p>
          <ul>
            <li><MI name="check" size={14} style={{ color: theme.primary }} /> Order ID otomatis dibuat (ORD-YYMMDD-NNN)</li>
            <li><MI name="check" size={14} style={{ color: theme.primary }} /> Link tracking dikirim via WhatsApp ke customer</li>
            <li><MI name="check" size={14} style={{ color: theme.primary }} /> Tahap DP otomatis ditandai sebagai stage aktif</li>
          </ul>
        </div>
      </div>

      <div className="baru-actions">
        <button type="button" className="baru-cancel" onClick={() => navigate("admin-dashboard")}>Batal</button>
        <button type="submit" className="baru-submit"
          style={{ background: `linear-gradient(135deg, ${theme.primary}, ${theme.secondary})`, boxShadow: `0 8px 20px ${theme.primary}45` }}>
          <MI name="check" size={16} /> Buat Pesanan
        </button>
      </div>

      <style>{`
        .baru { display: flex; flex-direction: column; gap: 14px; }
        .baru-row { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
        .baru-field { display: flex; flex-direction: column; margin-bottom: 12px; }
        .baru-field:last-child { margin-bottom: 0; }
        .baru-field label { font-size: 0.7rem; font-weight: 800; text-transform: uppercase; letter-spacing: 0.4px; margin-bottom: 5px; color: #475569; }
        .baru-field input, .baru-field textarea {
          padding: 10px 12px; border: 1.5px solid #e5e7eb; border-radius: 10px;
          font-family: inherit; font-size: 0.86rem; color: #1d1e20;
          background: white; outline: none; transition: border-color 0.15s;
        }
        .baru-field input:focus, .baru-field textarea:focus { border-color: ${theme.primary}; box-shadow: 0 0 0 3px ${theme.primary}1a; }
        .baru-field textarea { resize: vertical; min-height: 60px; }
        .baru-summary { display: flex; gap: 14px; }
        .baru-sum-label { font-size: 0.78rem; font-weight: 800; color: #1d1e20; margin-bottom: 6px; }
        .baru-summary ul { list-style: none; padding: 0; }
        .baru-summary li {
          display: flex; align-items: center; gap: 6px;
          font-size: 0.78rem; color: #475569; padding: 2px 0;
        }
        .baru-actions { display: flex; justify-content: flex-end; gap: 10px; }
        .baru-cancel {
          padding: 10px 18px; background: white; border: 1.5px solid #e5e7eb; border-radius: 10px;
          font-weight: 700; font-size: 0.85rem; cursor: pointer; color: #475569;
        }
        .baru-submit {
          padding: 10px 18px; color: white; border: none; border-radius: 10px;
          font-weight: 800; font-size: 0.88rem; cursor: pointer;
          display: inline-flex; align-items: center; gap: 6px;
        }
      `}</style>
    </form>
  );
}

// ═══════════════════════════════════════════════════════
// 5) PENGATURAN
// ═══════════════════════════════════════════════════════
function AdminPengaturan({ theme }) {
  const [form, setForm] = useS({
    notif_dp: true, notif_potong: true, notif_jahit: true, notif_packing: true, notif_kirim: true,
    interval: "15",
    template_dp: "Halo {{nama}}! Pesanan {{order_id}} sudah kami terima ✨ DP terkonfirmasi. Lacak progress di {{link}}.",
  });

  return (
    <div className="set">
      <div className="ad-card dashed">
        <h2 className="ad-section-title"><MI name="person" size={16} />Profil Admin</h2>
        <div className="set-profile">
          <div className="set-avatar" style={{ background: `linear-gradient(135deg, ${theme.primary}, ${theme.secondary})` }}>A</div>
          <div>
            <p className="set-name">Admin Utama</p>
            <p className="set-email">admin1@damelkeun.com</p>
            <button className="set-edit-btn">Ubah Profil</button>
          </div>
        </div>
      </div>

      <div className="ad-card dashed">
        <h2 className="ad-section-title"><MI name="notifications" size={16} />Notifikasi WhatsApp Otomatis</h2>
        <p className="set-helper">Pilih tahap mana yang otomatis mengirim notif WA ke customer saat update.</p>
        <div className="set-toggles">
          {[
            { key: "notif_dp",      label: "DP Diterima",            icon: "payments" },
            { key: "notif_potong",  label: "Potong Kain Selesai",    icon: "content_cut" },
            { key: "notif_jahit",   label: "Jahit Selesai",          icon: "fact_check" },
            { key: "notif_packing", label: "Packing Selesai",        icon: "inventory_2" },
            { key: "notif_kirim",   label: "Pesanan Dikirim",        icon: "local_shipping" },
          ].map((t) => (
            <div key={t.key} className="set-toggle-row">
              <div className="set-toggle-info">
                <div className="set-toggle-ic" style={{ background: `${theme.primary}15`, color: theme.primary }}>
                  <MI name={t.icon} size={16} />
                </div>
                <span>{t.label}</span>
              </div>
              <button
                className={`set-switch ${form[t.key] ? "on" : ""}`}
                onClick={() => setForm((p) => ({ ...p, [t.key]: !p[t.key] }))}
                style={form[t.key] ? { background: theme.primary } : {}}
              >
                <span />
              </button>
            </div>
          ))}
        </div>
      </div>

      <div className="ad-card dashed">
        <h2 className="ad-section-title"><MI name="sync" size={16} />Interval Polling</h2>
        <p className="set-helper">Seberapa sering halaman tracking customer auto-refresh.</p>
        <div className="set-radio-row">
          {[
            { v: "10", l: "10 detik" },
            { v: "15", l: "15 detik (rekomendasi)" },
            { v: "30", l: "30 detik" },
            { v: "60", l: "1 menit" },
          ].map((opt) => (
            <label key={opt.v} className={`set-radio ${form.interval === opt.v ? "selected" : ""}`}
              style={form.interval === opt.v ? { borderColor: theme.primary, background: `${theme.primary}10`, color: theme.primary } : {}}>
              <input type="radio" name="interval" checked={form.interval === opt.v}
                onChange={() => setForm((p) => ({ ...p, interval: opt.v }))} />
              {opt.l}
            </label>
          ))}
        </div>
      </div>

      <div className="ad-card dashed">
        <h2 className="ad-section-title"><MI name="chat" size={16} />Template Pesan WA — DP Diterima</h2>
        <p className="set-helper">Variabel tersedia: <code>{`{{nama}}`}</code>, <code>{`{{order_id}}`}</code>, <code>{`{{link}}`}</code></p>
        <textarea className="set-textarea" value={form.template_dp}
          onChange={(e) => setForm((p) => ({ ...p, template_dp: e.target.value }))} rows={3} />
        <div className="set-preview" style={{ background: `${theme.primary}08`, borderLeft: `3px solid ${theme.primary}` }}>
          <p className="set-preview-label">PREVIEW</p>
          <p>{form.template_dp.replace("{{nama}}", "Pak Bayu").replace("{{order_id}}", "ORD-260526-001").replace("{{link}}", "damelkeun.id/order/ORD-260526-001")}</p>
        </div>
      </div>

      <div className="set-actions">
        <button className="baru-submit"
          style={{ background: `linear-gradient(135deg, ${theme.primary}, ${theme.secondary})`, boxShadow: `0 8px 20px ${theme.primary}45`, padding: "10px 18px", color: "white", border: "none", borderRadius: 10, fontWeight: 800, fontSize: "0.88rem", cursor: "pointer", display: "inline-flex", alignItems: "center", gap: 6 }}>
          <MI name="save" size={16} /> Simpan Pengaturan
        </button>
      </div>

      <style>{`
        .set { display: flex; flex-direction: column; gap: 14px; }
        .set-helper { font-size: 0.78rem; color: #727586; margin-top: -8px; margin-bottom: 12px; }
        .set-helper code { background: #f2f3f6; padding: 1px 5px; border-radius: 4px; font-size: 0.72rem; }
        .set-profile { display: flex; align-items: center; gap: 16px; }
        .set-avatar {
          width: 60px; height: 60px; border-radius: 50%;
          display: flex; align-items: center; justify-content: center;
          color: white; font-weight: 800; font-size: 1.4rem;
        }
        .set-name { font-size: 1rem; font-weight: 800; }
        .set-email { font-size: 0.82rem; color: #727586; margin-bottom: 8px; }
        .set-edit-btn {
          padding: 6px 12px; background: white; border: 1.5px solid #e5e7eb; border-radius: 8px;
          font-weight: 700; font-size: 0.76rem; cursor: pointer; color: #475569;
        }
        .set-toggles { display: flex; flex-direction: column; }
        .set-toggle-row {
          display: flex; align-items: center; justify-content: space-between;
          padding: 10px 0; border-bottom: 1px solid #f3f4f6;
        }
        .set-toggle-row:last-child { border-bottom: none; }
        .set-toggle-info { display: flex; align-items: center; gap: 10px; font-size: 0.85rem; font-weight: 600; color: #1d1e20; }
        .set-toggle-ic { width: 32px; height: 32px; border-radius: 8px; display: flex; align-items: center; justify-content: center; }
        .set-switch {
          position: relative; width: 40px; height: 22px;
          background: #cbd5e1; border: none; border-radius: 999px;
          cursor: pointer; transition: background 0.2s;
        }
        .set-switch span {
          position: absolute; top: 2px; left: 2px;
          width: 18px; height: 18px; background: white; border-radius: 50%;
          transition: transform 0.2s; box-shadow: 0 1px 3px rgba(0,0,0,0.15);
        }
        .set-switch.on span { transform: translateX(18px); }
        .set-radio-row { display: grid; grid-template-columns: repeat(2, 1fr); gap: 8px; }
        .set-radio {
          padding: 10px 12px; border: 1.5px solid #e5e7eb; border-radius: 10px;
          font-size: 0.82rem; font-weight: 600; cursor: pointer; color: #475569;
          display: flex; align-items: center; gap: 8px;
          transition: all 0.15s;
        }
        .set-radio input { accent-color: ${theme.primary}; }
        .set-textarea {
          width: 100%; padding: 10px 12px; border: 1.5px solid #e5e7eb; border-radius: 10px;
          font-family: inherit; font-size: 0.85rem; color: #1d1e20;
          background: white; outline: none; resize: vertical; min-height: 70px;
        }
        .set-textarea:focus { border-color: ${theme.primary}; }
        .set-preview { padding: 10px 12px; margin-top: 10px; border-radius: 0 8px 8px 0; }
        .set-preview-label { font-size: 0.62rem; font-weight: 800; opacity: 0.6; letter-spacing: 0.5px; margin-bottom: 4px; color: ${theme.primary}; }
        .set-preview p:last-child { font-size: 0.82rem; line-height: 1.5; color: #1d1e20; }
        .set-actions { display: flex; justify-content: flex-end; }
      `}</style>
    </div>
  );
}

window.AdminShell        = AdminShell;
window.AdminDashboard    = AdminDashboard;
window.AdminDaftar       = AdminDaftar;
window.AdminDetail       = AdminDetail;
window.AdminBaru         = AdminBaru;
window.AdminPengaturan   = AdminPengaturan;
