/* =============================================================
   MyChartsPage.jsx — "خرايطي" / My Charts library (page-22)
   -----
   Lists saved charts from ChartStore, set-active / delete / create.
   Browser build: classic <script type="text/babel">; window.MyChartsPage
   ============================================================= */
(function () {
  const { useState } = React;

  const T = {
    ar: { title: "خرايطي", sub: "كل الخرائط التي أنشأتها محفوظة هنا. اختر خريطة لتفعيلها عبر التطبيق.",
      newc: "إنشاء خريطة جديدة", active: "نشطة", empty: "لا توجد خرائط بعد — ابدأ بإنشاء خريطتك الأولى.",
      view: "عرض الخريطة", born: "وُلد", del_q: "حذف هذه الخريطة؟", edit: "تعديل" },
    en: { title: "My Charts", sub: "Every chart you've created is saved here. Pick one to make it active across the app.",
      newc: "Create a new chart", active: "Active", empty: "No charts yet — start by creating your first.",
      view: "View chart", born: "Born", del_q: "Delete this chart?", edit: "Edit" },
  };

  window.MyChartsPage = function MyChartsPage({ lang, onRoute }) {
    const ar = lang === "ar";
    const t = T[lang] || T.ar;
    const [, force] = useState(0);
    const charts = window.ChartStore ? ChartStore.listCharts() : [];
    const activeId = window.ChartStore ? ChartStore.activeId() : null;

    function activate(id) { ChartStore.setActiveChart(id); onRoute("overview"); }
    async function del(e, id) {
      e.stopPropagation();
      if (!confirm(t.del_q)) return;
      try {
        await ChartStore.deleteChart(id);
        force((x) => x + 1);
      } catch (error) {
        window.alert(lang === "ar" ? "ما قدرناش نحذف الشارت. جرّب تاني." : "The chart could not be deleted. Try again.");
      }
    }
    function edit(e, id) { e.stopPropagation(); onRoute(`create/${id}`); }

    return (
      <>
        <PageHeader title={t.title} sub={t.sub} lang={lang} />
        <div className="mc-wrap">
          {charts.length === 0 ? (
            <div className="mc-grid">
              <div className="mc-new card-glass" onClick={() => onRoute("create")}>
                <span className="mc-new-i"><Icon.plus size={24} /></span>
                <strong>{t.newc}</strong>
              </div>
            </div>
          ) : (
            <div className="mc-grid">
              <div className="mc-new card-glass" onClick={() => onRoute("create")}>
                <span className="mc-new-i"><Icon.plus size={24} /></span>
                <strong>{t.newc}</strong>
              </div>
              {charts.map((rec) => {
                const c = rec.chart;
                const isActive = rec.id === activeId;
                return (
                  <div key={rec.id} className={`mc-card card-glass ${isActive ? "active" : ""}`} onClick={() => activate(rec.id)}>
                    <div className="mc-card-head">
                      <span className="mc-name">{(ar ? (rec.nameAr || rec.nameEn) : (rec.nameEn || rec.nameAr)) || rec.name || "—"}</span>
                      {isActive && <span className="mc-active-tag">{t.active}</span>}
                    </div>
                    <div className="mc-meta">
                      <span className="mc-chip">{ar ? c.type_ar : c.type_en}</span>
                      <span className="mc-chip">{c.profile}</span>
                      <span className="mc-chip">{ar ? c.authority_ar : c.authority_en}</span>
                      <span className="mc-chip">{ar ? c.definition_ar : c.definition_en}</span>
                    </div>
                    <div className="mc-foot">
                      <span>{t.born}: {ar ? (c.meta.placeAr || c.meta.placeEn) : (c.meta.placeEn || c.meta.placeAr)}</span>
                      <div className="mc-foot-actions">
                        <button className="mc-edit" onClick={(e) => edit(e, rec.id)} title={t.edit}><Icon.edit size={14} /></button>
                        <button className="mc-del" onClick={(e) => del(e, rec.id)} title={t.del_q}><Icon.trash size={15} /></button>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </>
    );
  };
})();
