// Client dashboard
const Dashboard = ({ t, lang, setPage, setSelectedParcel }) => {
  const data = window.DAOOB_DATA;
  const [tab, setTab] = React.useState("active");
  const [filter, setFilter] = React.useState("all");

  const filtered = data.studies.filter(s => {
    if (filter === "all") return true;
    if (filter === "active") return s.status === "progress";
    if (filter === "review") return s.status === "review";
    if (filter === "done")   return s.status === "done";
    return true;
  });

  const portfolioValue = data.studies.reduce((acc, s) => {
    const parcel = data.parcels.find(p => p.id === s.parcelId);
    if (!parcel?.price) return acc;
    return acc + parcel.price * parcel.area;
  }, 0);

  return (
    <div className="dash-shell">
      <aside className="dash-side">
        <div className="who">
          <div className="n">{lang === "ar" ? "محمد العنزي" : "Mohammed Al-Anazi"}</div>
          <div className="e">m.alanazi@example.sa</div>
        </div>
        <ul className="dash-nav">
          <li><button className={tab === "active" ? "on" : ""} onClick={() => setTab("active")}><Icon name="file" size={14}/> {t.dash.tabs.active}</button></li>
          <li><button className={tab === "parcels" ? "on" : ""} onClick={() => setTab("parcels")}><Icon name="map" size={14}/> {t.dash.tabs.parcels}</button></li>
          <li><button className={tab === "reports" ? "on" : ""} onClick={() => setTab("reports")}><Icon name="chart" size={14}/> {t.dash.tabs.reports}</button></li>
          <li><button className={tab === "billing" ? "on" : ""} onClick={() => setTab("billing")}><Icon name="wallet" size={14}/> {t.dash.tabs.billing}</button></li>
        </ul>
        <hr className="hr" style={{ margin: "20px 0" }}/>
        <ul className="dash-nav">
          <li><button><Icon name="settings" size={14}/> {lang === "ar" ? "الإعدادات" : "Settings"}</button></li>
        </ul>
      </aside>

      <main className="dash-main">
        <div className="between">
          <div>
            <h1 className="t-h1" style={{ margin: 0 }}>{t.dash.h1}</h1>
            <p style={{ color: "var(--ink-500)", marginTop: 8 }}>{t.dash.sub}</p>
          </div>
          <div style={{ display: "flex", gap: 12 }}>
            <button className="btn btn-outline" onClick={() => setPage("map")}><Icon name="map" size={14}/> {t.dash.open_map}</button>
            <button className="btn btn-primary" onClick={() => setPage("request")}><Icon name="plus" size={14}/> {t.dash.new_study}</button>
          </div>
        </div>

        {/* Usage meter — subscription quota */}
        {(() => {
          const used = 23, allocated = 30, daysLeft = 12, carryOver = 4;
          const pct = (used / allocated) * 100;
          const remaining = allocated - used;
          return (
            <div className="usage-meter">
              <div className="um-h">
                <div>
                  <div className="um-plan">
                    <Icon name="shield" size={12}/>
                    {lang === "ar" ? "باقة احترافية · شهرية" : "Professional plan · monthly"}
                  </div>
                  <div className="um-title">{lang === "ar" ? "استخدامك هذا الشهر" : "Your usage this month"}</div>
                </div>
                <button className="btn btn-gold btn-sm" onClick={() => setPage("services")}>
                  {lang === "ar" ? "شراء دراسات إضافية" : "Buy extra credits"} <Icon name="plus" size={12}/>
                </button>
              </div>
              <div className="um-stats">
                <div className="um-stat"><div className="um-v t-num">{used}</div><div className="um-l">{lang === "ar" ? "مستخدم" : "Used"}</div></div>
                <div className="um-stat"><div className="um-v t-num" style={{ color: "var(--green-700)" }}>{remaining}</div><div className="um-l">{lang === "ar" ? "متبقي" : "Remaining"}</div></div>
                <div className="um-stat"><div className="um-v t-num">{daysLeft}<small>{lang === "ar" ? " يوم" : "d"}</small></div><div className="um-l">{lang === "ar" ? "حتى التجديد" : "Until renewal"}</div></div>
                <div className="um-stat"><div className="um-v t-num" style={{ color: "var(--gold-700)" }}>+{carryOver}</div><div className="um-l">{lang === "ar" ? "مُرحَّل من الشهر السابق" : "Carried over"}</div></div>
              </div>
              <div className="um-bar">
                <div className="um-bar-fill" style={{ width: pct + "%" }}/>
                <span className="um-bar-tag" style={{ insetInlineStart: pct + "%" }}>{used}/{allocated}</span>
              </div>
            </div>
          );
        })()}

        {/* KPIs */}
        <div className="dash-kpis">
          <div className="dash-kpi">
            <div className="lbl">{t.dash.pf_value}</div>
            <div className="val">{(portfolioValue / 1e6).toFixed(1)}M</div>
            <div className="d">SAR · {lang === "ar" ? "تقديري" : "indicative"}</div>
          </div>
          <div className="dash-kpi">
            <div className="lbl">{t.dash.pf_avg_roi}</div>
            <div className="val">14.2%</div>
            <div className="d">{lang === "ar" ? "متوسط 6 دراسات" : "across 6 studies"}</div>
          </div>
          <div className="dash-kpi">
            <div className="lbl">{t.dash.pf_parcels}</div>
            <div className="val">12</div>
            <div className="d">{lang === "ar" ? "3 جديدة" : "3 new this month"}</div>
          </div>
          <div className="dash-kpi">
            <div className="lbl">{t.dash.pf_alerts}</div>
            <div className="val" style={{ color: "var(--gold-700)" }}>2</div>
            <div className="d">{lang === "ar" ? "تغيّر اشتراطات" : "zoning changes"}</div>
          </div>
        </div>

        {/* Filters */}
        <div style={{ display: "flex", gap: 8, marginBottom: 16 }}>
          {[
            { k: "all",    lbl: t.dash.filter_all },
            { k: "active", lbl: t.dash.filter_active },
            { k: "review", lbl: t.dash.filter_review },
            { k: "done",   lbl: t.dash.filter_done },
          ].map(f => (
            <button
              key={f.k}
              className={"btn btn-sm" + (filter === f.k ? " btn-primary" : " btn-ghost")}
              onClick={() => setFilter(f.k)}
            >{f.lbl}</button>
          ))}
        </div>

        {/* Studies table */}
        <table className="studies-table">
          <thead>
            <tr>
              <th>{lang === "ar" ? "المرجع" : "Reference"}</th>
              <th>{lang === "ar" ? "القطعة" : "Parcel"}</th>
              <th>{lang === "ar" ? "نوع الدراسة" : "Study type"}</th>
              <th>{lang === "ar" ? "الحالة" : "Status"}</th>
              <th>{t.dash.assigned}</th>
              <th style={{ textAlign: "end" }}>{t.dash.eta}</th>
              <th style={{ textAlign: "end" }}>{lang === "ar" ? "السعر" : "Price"}</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(s => {
              const p = data.parcels.find(x => x.id === s.parcelId);
              const district = p ? data.districts[p.district][lang] : "—";
              return (
                <tr key={s.ref}>
                  <td className="ref">{s.ref}</td>
                  <td>
                    <div style={{ fontWeight: 500 }}>{district}</div>
                    <div className="ref">{s.parcelId}</div>
                  </td>
                  <td>{s.type[lang]}</td>
                  <td>
                    <span className={"status-pill status-" + s.status}>
                      <span className="status-dot"/>
                      {s.status === "progress" ? t.dash.filter_active : s.status === "review" ? t.dash.filter_review : t.dash.filter_done}
                    </span>
                    {s.status !== "done" && (
                      <div className="progress-bar"><div style={{ width: s.progress + "%" }}/></div>
                    )}
                  </td>
                  <td>{s.assignee}</td>
                  <td style={{ textAlign: "end" }}>{s.eta}</td>
                  <td style={{ textAlign: "end", fontFamily: "var(--font-serif)" }}>{s.price.toLocaleString()}</td>
                  <td style={{ textAlign: "end" }}>
                    <button className="btn btn-ghost btn-sm" onClick={() => { setSelectedParcel(s.parcelId); setPage(s.status === "done" ? "report" : "map"); }}>
                      {s.status === "done" ? (lang === "ar" ? "افتح التقرير" : "Open report") : (lang === "ar" ? "عرض" : "View")} <Icon name="arrow-right" size={12}/>
                    </button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>

        {/* Activity feed */}
        <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 24, marginTop: 40 }}>
          <div>
            <h3 className="t-h3" style={{ marginBottom: 16 }}>{t.dash.activity_h}</h3>
            <div className="card" style={{ padding: 0 }}>
              {[
                { t: "Valuation Agent uploaded interim valuation for DAO-2026-0184", time: "2h ago", icon: "file" },
                { t: "Zoning change detected on RYD-3402-HT", time: "5h ago", icon: "shield" },
                { t: "Market Agent completed cross-check on DAO-2026-0182", time: "Yesterday", icon: "users" },
                { t: "Comparable transaction added · RYD-7204-RW · 4.1M SAR", time: "Yesterday", icon: "chart" },
                { t: "Report delivered: Highest & Best Use, RYD-3402-HT", time: "9 May", icon: "check" },
              ].map((a, i) => (
                <div key={i} style={{ display: "flex", gap: 14, padding: "14px 18px", borderBottom: i === 4 ? 0 : "1px solid var(--hairline)" }}>
                  <div style={{ width: 32, height: 32, borderRadius: 6, background: "var(--green-50)", color: "var(--green-700)", display: "grid", placeItems: "center", flexShrink: 0 }}>
                    <Icon name={a.icon} size={14}/>
                  </div>
                  <div style={{ flex: 1, fontSize: 14 }}>
                    <div>{a.t}</div>
                    <div style={{ color: "var(--ink-400)", fontSize: 12, marginTop: 2 }}>{a.time}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
          <div>
            <h3 className="t-h3" style={{ marginBottom: 16 }}>{t.dash.portfolio_h}</h3>
            <div className="card" style={{ padding: 24 }}>
              <div style={{ fontSize: 12, color: "var(--ink-400)", textTransform: "uppercase", letterSpacing: "0.06em" }}>{lang === "ar" ? "توزيع القطع" : "Parcels by district"}</div>
              <div style={{ marginTop: 20, display: "flex", flexDirection: "column", gap: 10 }}>
                {[
                  { d: "Olaya", c: 4, p: 33 },
                  { d: "KAFD",  c: 3, p: 25 },
                  { d: "Malqa", c: 2, p: 17 },
                  { d: "Hittin",c: 2, p: 17 },
                  { d: "Other", c: 1, p: 8 },
                ].map((r, i) => (
                  <div key={i}>
                    <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13 }}>
                      <span>{r.d}</span><span className="t-num">{r.c}</span>
                    </div>
                    <div className="progress-bar" style={{ marginTop: 6 }}><div style={{ width: r.p + "%", background: "var(--gold-500)" }}/></div>
                  </div>
                ))}
              </div>
              <hr className="hr" style={{ margin: "24px 0" }}/>
              <div style={{ fontSize: 12, color: "var(--ink-400)", textTransform: "uppercase", letterSpacing: "0.06em" }}>{lang === "ar" ? "نشاط 90 يومًا" : "Activity 90d"}</div>
              <div className="spark" style={{ marginTop: 14, height: 48 }}>
                {[12,16,10,22,18,28,24,32,28,38,42,36,48,52,44,58,48,62,56,68,72,64,76,80].map((v,i) => (
                  <i key={i} style={{ height: v + "%" }}/>
                ))}
              </div>
            </div>
          </div>
        </div>
      </main>
    </div>
  );
};

Object.assign(window, { Dashboard });
