/* eslint-disable */
/* =============================================================
   ReportPage — Spade's Life Explained
   -----
   Sub-views from the hash param:
     #/report          → preview (معاينة التقرير)
     #/report/pdf      → PDF export options (خيارات تصدير PDF)
     #/report/success  → download success (تم التنزيل)
     #/report/share    → share link (مشاركة التقرير)
   Reads globals: I18N, Icon, PageHeader, Btn, CHART_SUMMARY, HDContent,
     InteractiveBodygraph, HDToast
   ============================================================= */
(function () {
  const { useState } = React;

  const LinkGlyph = ({ size = 16 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M10 13a5 5 0 0 0 7 0l2-2a5 5 0 0 0-7-7l-1 1"/><path d="M14 11a5 5 0 0 0-7 0l-2 2a5 5 0 0 0 7 7l1-1"/></svg>
  );
  const Folder = ({ size = 16 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/></svg>
  );
  const FileGlyph = ({ size = 16 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M6 3h9l4 4v14a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1z"/><path d="M9 13h6M9 16h4"/></svg>
  );

  window.ReportPage = function ReportPage({ lang, onRoute, param }) {
    const ar = lang === "ar";
    const view = param || "preview";
    const tt = (a, e) => (ar ? a : e);
    const toast = (type, title, msg) => window.HDToast && HDToast.show({ type, title, msg });
    if (view === "pdf") return <Pdf ar={ar} onRoute={onRoute} tt={tt} toast={toast} />;
    if (view === "success") return <Success ar={ar} onRoute={onRoute} tt={tt} toast={toast} />;
    if (view === "share") return <Share ar={ar} onRoute={onRoute} tt={tt} toast={toast} />;
    return <Preview ar={ar} onRoute={onRoute} tt={tt} toast={toast} />;
  };

  // small cover used in preview + pdf live preview
  function CoverCard({ ar, compact }) {
    const S = window.CHART_SUMMARY || {};
    return (
      <div className={`rep-cover ${compact ? "compact" : ""}`}>
        <div className="rep-cover-brand"><span className="rep-cover-orb"><Icon.sparkle size={16} /></span><div><strong>HUMAN DESIGN</strong><span>{ar ? "رحلة الوعي" : "Journey of awareness"}</span></div></div>
        <h3 className="rep-cover-title">{ar ? "خارطة الوعي" : "Map of Awareness"}</h3>
        <p className="rep-cover-sub">{ar ? "تقرير القراءة الإنسانية" : "Human reading report"}</p>
        {!compact && window.InteractiveBodygraph && (
          <div className="rep-cover-bg"><InteractiveBodygraph lang={ar ? "ar" : "en"} selectable={false} popups={false} width={150} height={230} showGateNumbers={false} showSilhouette={true} /></div>
        )}
        <div className="rep-cover-meta">
          <div><em>{ar ? "النوع" : "Type"}</em><span>{ar ? S.type_ar : S.type_en}</span></div>
          <div><em>{ar ? "الاستراتيجية" : "Strategy"}</em><span>{ar ? S.strategy_ar : S.strategy_en}</span></div>
          <div><em>{ar ? "السلطة الداخلية" : "Authority"}</em><span>{ar ? S.authority_ar : S.authority_en}</span></div>
        </div>
        <div className="rep-cover-date">{ar ? "تاريخ القراءة: 25 مايو 2025" : "Reading date: May 25, 2025"}</div>
      </div>
    );
  }

  // ════════════════════════════ PREVIEW ════════════════════════════
  function Preview({ ar, onRoute, tt, toast }) {
    const pages = [
      tt("الغلاف", "Cover"), tt("المحتويات", "Contents"), tt("ملخص خريطتك", "Chart summary"),
      tt("النوع والاستراتيجية", "Type & strategy"), tt("السلطة الداخلية", "Inner authority"), tt("مراكزك", "Your centers"),
    ];
    return (
      <div className="page page-report">
        <PageHeader title={tt("معاينة التقرير", "Report preview")} sub={tt("استعرض تقريرك قبل التصدير أو المشاركة.", "Review your report before exporting or sharing.")} lang={ar ? "ar" : "en"} />
        <div className="rep-grid">
          <div className="bil-card rep-preview-col" data-galaxy-ui>
            <h3 className="bil-h">{tt("معاينة التقرير", "Report preview")}</h3>
            <CoverCard ar={ar} />
          </div>

          <div className="bil-card rep-pages-col" data-galaxy-ui>
            <h3 className="bil-h center">{tt("صفحات التقرير", "Report pages")}</h3>
            <div className="rep-thumbs">
              {pages.map((p, i) => (
                <button key={i} type="button" className={`rep-thumb ${i === 0 ? "active" : ""}`} onClick={() => toast("info", tt("معاينة الصفحة", "Page preview"), p)}>
                  <span className="rep-thumb-canvas"><FileGlyph size={20} /></span>
                  <span className="rep-thumb-label">{p}</span>
                  <span className="rep-thumb-num">{i + 1}</span>
                </button>
              ))}
            </div>
            <div className="rep-pager"><button type="button"><Icon.chevRight size={16} /></button><span>1 / 12</span><button type="button"><Icon.chevLeft size={16} /></button></div>
          </div>

          <aside className="bil-side">
            <div className="bil-card" data-galaxy-ui>
              <h3 className="bil-h">{tt("معلومات التقرير", "Report info")}</h3>
              <div className="rep-info">
                <div className="rep-info-row"><span><FileGlyph size={13} /> {tt("اسم التقرير", "Report name")}</span><b>{tt("تقرير القراءة الإنسانية", "Human reading report")}</b></div>
                <div className="rep-info-row"><span><Icon.overview size={13} /> {tt("نوع التقرير", "Report type")}</span><b>{tt("تقرير شامل", "Comprehensive")}</b></div>
                <div className="rep-info-row"><span><Icon.clock size={13} /> {tt("آخر تحديث", "Last update")}</span><b>{tt("25 مايو 2025، 10:45", "May 25, 2025 · 10:45")}</b></div>
                <div className="rep-info-row"><span><Icon.bookOpen size={13} /> {tt("عدد الصفحات", "Pages")}</span><b>{tt("12 صفحة", "12 pages")}</b></div>
                <div className="rep-info-row"><span><Icon.globe size={13} /> {tt("اللغة", "Language")}</span><b>{ar ? "العربية" : "English"}</b></div>
              </div>
            </div>
            <div className="bil-card rep-actions" data-galaxy-ui>
              <h3 className="bil-h">{tt("الإجراءات", "Actions")}</h3>
              <button type="button" className="rep-act primary" onClick={() => onRoute("report/pdf")}><Icon.download size={15} /> {tt("تصدير PDF", "Export PDF")}</button>
              <button type="button" className="rep-act" onClick={() => onRoute("report/share")}><LinkGlyph size={15} /> {tt("نسخ رابط المشاركة", "Copy share link")}</button>
              <button type="button" className="rep-act" onClick={() => onRoute("report/success")}><Icon.download size={15} /> {tt("تنزيل", "Download")}</button>
              <div className="rep-act-row">
                <button type="button" className="rep-act ghost" onClick={() => toast("info", tt("تخصيص التقرير", "Customize"), tt("اختر الأقسام التي تريد تضمينها.", "Pick which sections to include."))}><Icon.settings size={14} /> {tt("تخصيص التقرير", "Customize")}</button>
                <button type="button" className="rep-act ghost" onClick={() => onRoute("overview")}><Icon.chevLeft size={14} /> {tt("الرجوع", "Back")}</button>
              </div>
              <p className="rep-hint"><Icon.help size={13} /> {tt("يمكنك تخصيص محتوى التقرير قبل التصدير باختيار الأقسام التي تريد تضمينها.", "You can customize the report before exporting by choosing which sections to include.")}</p>
            </div>
          </aside>
        </div>
      </div>
    );
  }

  // ════════════════════════════ PDF OPTIONS ════════════════════════════
  function Pdf({ ar, onRoute, tt, toast }) {
    const [size, setSize] = useState("A4");
    const [orient, setOrient] = useState("portrait");
    const [plang, setPlang] = useState(ar ? "ar" : "en");
    const [quality, setQuality] = useState("high");
    const [tg, setTg] = useState({ cover: true, summary: true, full: true, brand: true });
    const Seg = ({ opts, val, onPick }) => (
      <div className="rep-seg">{opts.map((o) => <button type="button" key={o.id} className={val === o.id ? "active" : ""} onClick={() => onPick(o.id)}>{o.label}</button>)}</div>
    );
    const Toggle = ({ on, onClick }) => <button type="button" className={`rep-toggle ${on ? "on" : ""}`} onClick={onClick}><span /></button>;
    const rows = [
      { ic: <FileGlyph size={16} />, t: tt("حجم الصفحة", "Page size"), s: tt("اختر حجم الصفحة المناسب", "Pick the page size"), ctrl: <Seg opts={[{ id: "A4", label: "A4" }, { id: "Letter", label: "Letter" }]} val={size} onPick={setSize} /> },
      { ic: <Icon.overview size={16} />, t: tt("الاتجاه", "Orientation"), s: tt("حدّد اتجاه الصفحة", "Page orientation"), ctrl: <Seg opts={[{ id: "landscape", label: tt("أفقي", "Landscape") }, { id: "portrait", label: tt("عمودي", "Portrait") }]} val={orient} onPick={setOrient} /> },
      { ic: <Icon.globe size={16} />, t: tt("اللغة", "Language"), s: tt("اختر لغة المحتوى في الملف", "Content language"), ctrl: <Seg opts={[{ id: "en", label: "English" }, { id: "ar", label: "العربية" }]} val={plang} onPick={setPlang} /> },
      { ic: <Icon.bookOpen size={16} />, t: tt("تضمين الغلاف", "Include cover"), s: tt("إضافة صفحة غلاف إلى الملف", "Add a cover page"), ctrl: <Toggle on={tg.cover} onClick={() => setTg({ ...tg, cover: !tg.cover })} /> },
      { ic: <Icon.overview size={16} />, t: tt("تضمين ملخص الخريطة", "Include chart summary"), s: tt("إضافة ملخص خريطتك الأساسية", "Add your chart summary"), ctrl: <Toggle on={tg.summary} onClick={() => setTg({ ...tg, summary: !tg.summary })} /> },
      { ic: <Icon.guide size={16} />, t: tt("تضمين التحليل الكامل", "Include full analysis"), s: tt("تضمين جميع الأقسام والتحليلات", "All sections & analyses"), ctrl: <Toggle on={tg.full} onClick={() => setTg({ ...tg, full: !tg.full })} /> },
      { ic: <Icon.crown size={16} />, t: tt("إظهار شعار سبيد", "Show Spade mark"), s: tt("إضافة شعار الموقع أسفل الملف", "Add the site mark in the footer"), ctrl: <Toggle on={tg.brand} onClick={() => setTg({ ...tg, brand: !tg.brand })} />, gold: true },
      { ic: <Icon.flash size={16} />, t: tt("جودة التصدير", "Export quality"), s: tt("اختر جودة الصور والنصوص", "Image & text quality"), ctrl: <Seg opts={[{ id: "standard", label: tt("قياسية", "Standard") }, { id: "high", label: tt("عالية", "High") }]} val={quality} onPick={setQuality} /> },
    ];
    return (
      <div className="page page-report">
        <PageHeader title={tt("خيارات تصدير PDF", "PDF export options")} sub={tt("اختر إعدادات التصدير المناسبة قبل إنشاء ملف PDF.", "Choose your export settings before generating the PDF.")} lang={ar ? "ar" : "en"} />
        <div className="rep-grid2">
          <div className="bil-card rep-opts" data-galaxy-ui>
            {rows.map((r, i) => (
              <div key={i} className="rep-opt">
                <span className={`rep-opt-ic ${r.gold ? "gold" : ""}`}>{r.ic}</span>
                <div className="rep-opt-tx"><strong>{r.t}</strong><span>{r.s}</span></div>
                <div className="rep-opt-ctrl">{r.ctrl}</div>
              </div>
            ))}
          </div>
          <aside className="bil-card rep-livecol" data-galaxy-ui>
            <h3 className="bil-h center">{tt("معاينة حية", "Live preview")}</h3>
            <CoverCard ar={ar} compact />
            <div className="rep-pager"><button type="button"><Icon.chevRight size={16} /></button><span>1 / 1</span><button type="button"><Icon.chevLeft size={16} /></button></div>
          </aside>
        </div>
        <div className="rep-confirm-bar">
          <Btn kind="ghost" onClick={() => onRoute("report")}>{tt("إلغاء", "Cancel")}</Btn>
          <button type="button" className="rep-confirm" onClick={() => onRoute("report/success")}><Icon.download size={16} /> {tt("تأكيد التصدير", "Confirm export")}</button>
        </div>
      </div>
    );
  }

  // ════════════════════════════ DOWNLOAD SUCCESS ════════════════════════════
  function Success({ ar, onRoute, tt, toast }) {
    return (
      <div className="page page-report rep-success">
        <div className="bil-card rep-success-card" data-galaxy-ui>
          <div className="bil-burst"><div className="bil-check"><Icon.check size={60} /></div></div>
          <h1 className="bil-success-title">{tt("تم تنزيل التقرير بنجاح", "Report downloaded")}</h1>
          <p className="bil-success-sub">{tt("تم حفظ التقرير على جهازك بنجاح، يمكنك فتحه الآن أو مشاركته مع من تريد.", "Your report is saved. Open it now or share it with whomever you like.")}</p>
          <div className="rep-file">
            <div className="rep-file-row"><span><FileGlyph size={14} /> {tt("اسم الملف", "File name")}</span><b>{tt("تقرير الحالة – 30 يوم.pdf", "30-day report.pdf")}</b></div>
            <div className="rep-file-row"><span><FileGlyph size={14} /> {tt("الصيغة", "Format")}</span><b>PDF</b></div>
            <div className="rep-file-row"><span><Icon.flash size={14} /> {tt("الحجم", "Size")}</span><b>2.48 {tt("ميجابايت", "MB")}</b></div>
            <div className="rep-file-row"><span><Icon.clock size={14} /> {tt("وقت التنزيل", "Downloaded")}</span><b>{tt("26 مايو 2025 – 14:32", "May 26, 2025 · 14:32")}</b></div>
          </div>
          <div className="rep-success-actions">
            <button type="button" className="rep-act ghost" onClick={() => onRoute("report/share")}><LinkGlyph size={14} /> {tt("نسخ رابط المشاركة", "Copy share link")}</button>
            <button type="button" className="rep-act ghost" onClick={() => toast("info", tt("فتح المجلد", "Open folder"), "")}><Folder size={14} /> {tt("فتح المجلد", "Open folder")}</button>
            <button type="button" className="rep-act primary" onClick={() => toast("info", tt("فتح الملف", "Opening file"), "")}><FileGlyph size={14} /> {tt("فتح الملف", "Open file")}</button>
          </div>
          <div className="rep-or"><span>{tt("أو", "or")}</span></div>
          <button type="button" className="rep-back" onClick={() => onRoute("report")}><Icon.chevLeft size={14} /> {tt("العودة إلى التقارير", "Back to reports")}</button>
        </div>
      </div>
    );
  }

  // ════════════════════════════ SHARE LINK ════════════════════════════
  function Share({ ar, onRoute, tt, toast }) {
    const [access, setAccess] = useState("view");
    const [expiry, setExpiry] = useState(false);
    const url = "https://humandesign.ai/share/report/abc123def4567890";
    const copy = () => { try { const p = navigator.clipboard && navigator.clipboard.writeText(url); if (p && p.catch) p.catch(() => {}); } catch (e) {} toast("success", tt("تم نسخ الرابط", "Link copied"), ""); };
    const perms = [
      { id: "view", ic: <Icon.eye size={15} />, t: tt("السماح بالعرض فقط", "View only"), s: tt("يمكن عرض التقرير فقط", "Report can only be viewed") },
      { id: "download", ic: <Icon.download size={15} />, t: tt("السماح بالتنزيل", "Allow download"), s: tt("يمكن عرض وتنزيل التقرير", "View and download") },
      { id: "restricted", ic: <Icon.users size={15} />, t: tt("عرض محدد", "Restricted"), s: tt("يتطلب تسجيل دخول", "Requires sign-in") },
    ];
    return (
      <div className="page page-report">
        <PageHeader title={tt("مشاركة التقرير", "Share report")} sub={tt("شارك تقرير رحلتك عبر رابط آمن وقابل للمشاركة.", "Share your journey report via a secure link.")} lang={ar ? "ar" : "en"} />
        <div className="rep-grid2">
          <div className="bil-main">
            <div className="bil-card" data-galaxy-ui>
              <div className="rep-share-head"><span className="bil-h"><span className="bil-h-ic"><LinkGlyph size={15} /></span> {tt("رابط المشاركة", "Share link")}</span><span className="rep-link-on"><i></i> {tt("الرابط نشط", "Active")}</span></div>
              <p className="rep-share-sub">{tt("يمكنك مشاركة هذا الرابط مع أي شخص لعرض تقريرك.", "Share this link with anyone to view your report.")}</p>
              <div className="rep-linkbox"><input readOnly value={url} /><button type="button" onClick={copy}><Icon.share size={14} /> {tt("نسخ الرابط", "Copy")}</button></div>
              <div className="rep-link-actions">
                <button type="button" className="rep-act ghost" onClick={() => toast("success", tt("تم إعادة إنشاء الرابط", "Link regenerated"), "")}><Icon.clock size={14} /> {tt("إعادة إنشاء الرابط", "Regenerate")}</button>
                <button type="button" className="rep-act warn" onClick={() => toast("info", tt("تم تعطيل الرابط", "Link disabled"), "")}><Icon.lock size={14} /> {tt("تعطيل الرابط", "Disable")}</button>
                <button type="button" className="rep-act danger" onClick={() => window.HDConfirm && HDConfirm.open({ title: tt("حذف الرابط؟", "Delete link?"), msg: tt("لن يعمل الرابط بعد الحذف.", "The link will stop working."), confirmText: tt("حذف", "Delete"), cancelText: tt("تراجع", "Back"), danger: true, onConfirm: () => { toast("success", tt("تم حذف الرابط", "Link deleted"), ""); onRoute("report"); } })}><Icon.trash size={14} /> {tt("حذف الرابط", "Delete")}</button>
              </div>
            </div>

            <div className="bil-card" data-galaxy-ui>
              <h3 className="bil-h"><span className="bil-h-ic"><Icon.lock size={15} /></span> {tt("أذونات الوصول", "Access permissions")}</h3>
              <p className="rep-share-sub">{tt("تحكّم في ما يمكن للمستلمين القيام به.", "Control what recipients can do.")}</p>
              <div className="rep-perms">
                {perms.map((p) => (
                  <button key={p.id} type="button" className={`rep-perm ${access === p.id ? "active" : ""}`} onClick={() => setAccess(p.id)}>
                    <span className="rep-perm-ic">{p.ic}</span>
                    <div><strong>{p.t}</strong><span>{p.s}</span></div>
                    {access === p.id && <span className="rep-perm-ok"><Icon.check size={12} /></span>}
                  </button>
                ))}
              </div>
              <div className="rep-expiry">
                <div><strong>{tt("تاريخ انتهاء الرابط", "Link expiry")}</strong><span>{tt("تحديد موعد انتهاء صلاحية الرابط (اختياري).", "Set an optional expiry date.")}</span></div>
                <button type="button" className={`rep-toggle ${expiry ? "on" : ""}`} onClick={() => setExpiry(!expiry)}><span /></button>
              </div>
              {expiry && <div className="bil-input rep-expiry-input"><input placeholder={tt("اختر التاريخ والوقت", "Pick date & time")} /><Icon.calendar size={14} /></div>}
              <p className="bil-note"><Icon.help size={13} /> {tt("سيتمكّن أي شخص لديه هذا الرابط من الوصول إلى التقرير وفقًا للأذونات المحددة أعلاه.", "Anyone with this link can access the report per the permissions above.")}</p>
            </div>
          </div>

          <aside className="bil-side">
            <div className="bil-card rep-linkstatus" data-galaxy-ui>
              <h3 className="bil-h center">{tt("حالة الرابط", "Link status")}</h3>
              <div className="rep-status-mark"><Icon.check size={30} /></div>
              <strong className="rep-status-on">{tt("الرابط نشط", "Link active")}</strong>
              <span className="rep-status-note">{tt("تم إنشاء الرابط بنجاح وهو جاهز للمشاركة.", "Created successfully and ready to share.")}</span>
            </div>
            <div className="bil-card" data-galaxy-ui>
              <div className="rep-stat"><span className="rep-stat-ic"><Icon.share size={15} /></span><div><strong>{tt("آخر مشاركة", "Last shared")}</strong><span>{tt("منذ 5 دقائق · نُسخ بواسطتك", "5 min ago · copied by you")}</span></div></div>
              <div className="rep-stat"><span className="rep-stat-ic"><Icon.eye size={15} /></span><div><strong>{tt("عدد مرات الفتح", "Open count")}</strong><span>12 · {tt("آخر فتح منذ 10 دقائق", "last open 10 min ago")}</span></div></div>
              <div className="rep-stat"><span className="rep-stat-ic"><Icon.lock size={15} /></span><div><strong>{tt("مستوى الوصول", "Access level")}</strong><span>{tt("عرض فقط · لا يمكن تنزيل التقرير", "View only · no download")}</span></div></div>
              <div className="rep-stat"><span className="rep-stat-ic"><Icon.calendar size={15} /></span><div><strong>{tt("تم الإنشاء في", "Created")}</strong><span>{tt("22 مايو 2025 · 10:30 صباحًا", "May 22, 2025 · 10:30")}</span></div></div>
            </div>
            <Btn kind="ghost" onClick={() => onRoute("report")}><Icon.chevLeft size={14} /> {tt("العودة إلى التقرير", "Back to report")}</Btn>
          </aside>
        </div>
      </div>
    );
  }
})();
