// Certificates — list and preview, modeled on the sample PDF

function CertificatesScreen({ ctx }) {
  const { registrations, selectedId, setSelectedId } = ctx;
  const certs = registrations.filter(r => r.certificateIssued);
  const selected = certs.find(r => r.id === selectedId) || certs[0];
  const [downloading, setDownloading] = React.useState(false);

  const handlePrint = () => {
    window.print();
  };

  const handleDownloadPDF = async () => {
    if (!window.html2pdf) {
      alert('PDF library ยังโหลดไม่เสร็จ กรุณารอสักครู่แล้วลองใหม่');
      return;
    }
    const el = document.getElementById('cert-preview-area');
    if (!el) return;
    setDownloading(true);
    try {
      await window.html2pdf().set({
        margin:     [8, 8, 8, 8],
        filename:   `${selected.arsNo || selected.id}.pdf`,
        image:      { type: 'jpeg', quality: 0.98 },
        html2canvas: { scale: 2, useCORS: true, logging: false },
        jsPDF:      { unit: 'mm', format: 'a4', orientation: 'portrait' },
      }).from(el).save();
    } catch (e) {
      console.error('PDF error:', e);
      alert('เกิดข้อผิดพลาดในการสร้าง PDF: ' + e.message);
    }
    setDownloading(false);
  };

  return (
    <div className="page">
      <div className="page__header">
        <div>
          <h1 className="page__title">Warranty Certificates</h1>
          <p className="page__sub">เอกสารรับรองที่ระบบสร้างให้อัตโนมัติหลังการอนุมัติ • {certs.length} ฉบับ</p>
        </div>
        <div className="page__actions">
          <button className="btn"><Icon name="download" size={14}/> Bulk download</button>
        </div>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "320px 1fr", gap: 16 }}>
        {/* List */}
        <div id="cert-list-panel" className="card" style={{ alignSelf: "start", maxHeight: "calc(100vh - 200px)", overflow: "hidden", display: "flex", flexDirection: "column" }}>
          <div className="card__header"><h3 className="card__title">All certificates</h3></div>
          <div style={{ overflowY: "auto" }}>
            {certs.map(r => (
              <div key={r.id} onClick={() => setSelectedId(r.id)}
                   style={{ padding: "12px 16px", borderBottom: "1px solid var(--border)", cursor: "pointer", background: selected?.id === r.id ? "var(--jt-navy-50)" : "transparent" }}>
                <div className="spread">
                  <span className="mono small" style={{ fontWeight: 600 }}>{r.arsNo || r.id}</span>
                  <Icon name="cert" size={14} color="var(--jt-red)"/>
                </div>
                <div style={{ marginTop: 4, fontSize: 13 }}>{r.customer.company}</div>
                <div className="muted small mono">{r.product.serial}</div>
              </div>
            ))}
          </div>
        </div>

        {/* Preview */}
        {selected && (
          <div>
            <div id="cert-action-bar" style={{ display: "flex", gap: 8, marginBottom: 12, justifyContent: "flex-end" }}>
              <button className="btn" disabled={downloading} onClick={handleDownloadPDF}>
                {downloading
                  ? <><Icon name="clock" size={14}/> กำลังสร้าง PDF…</>
                  : <><Icon name="download" size={14}/> Download PDF</>}
              </button>
              <button className="btn btn--primary" onClick={handlePrint}>
                <Icon name="external" size={14}/> Print
              </button>
            </div>
            <CertificatePreview r={selected} />
          </div>
        )}
      </div>
    </div>
  );
}

function CertificatePreview({ r }) {
  return (
    <div id="cert-preview-area" style={{ background: "#fff", boxShadow: "0 8px 24px rgba(11,21,49,0.12)", borderRadius: 6, overflow: "hidden", maxWidth: 820, margin: "0 auto", border: "1px solid var(--border)" }}>
      {/* Header band */}
      <div style={{ background: "linear-gradient(135deg, #0a1f5c 0%, #1a3a8f 60%, #2851b3 100%)", padding: "16px 28px", color: "#fff", position: "relative", overflow: "hidden" }}>
        {/* Decorative concentric arcs */}
        <svg style={{ position: "absolute", right: -60, top: -40, opacity: 0.18 }} width="280" height="280" viewBox="0 0 280 280">
          {[40, 70, 100, 130, 160].map(r2 => <circle key={r2} cx="180" cy="120" r={r2} fill="none" stroke="#5ec5ff" strokeWidth="0.7"/>)}
          {[...Array(20)].map((_, i) => {
            const angle = (i / 20) * Math.PI * 2;
            return <line key={i} x1={180 + Math.cos(angle)*40} y1={120 + Math.sin(angle)*40} x2={180 + Math.cos(angle)*160} y2={120 + Math.sin(angle)*160} stroke="#5ec5ff" strokeWidth="0.4"/>
          })}
        </svg>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", position: "relative" }}>
          <div>
            <div style={{ fontFamily: "var(--font-display)", fontWeight: 700, color: "var(--jt-red)", letterSpacing: "0.08em", fontSize: 22 }}>JOURNEY TECH</div>
            <div style={{ fontSize: 11, opacity: 0.75, marginTop: 4, letterSpacing: "0.04em" }}>
              98/369 Moo 10 Bangmaenang Bangyai Nonthaburi 11140
            </div>
            <div style={{ fontSize: 11, opacity: 0.75 }}>
              www.Journey-Tech.co.th • Line Official: @Journeytech
            </div>
          </div>
          <div style={{ textAlign: "right", fontSize: 10, letterSpacing: "0.14em", opacity: 0.6 }}>
            WARRANTY CERTIFICATE<br/>JOURNEY TECH CO., LTD.
          </div>
        </div>
      </div>

      <div style={{ padding: "20px 32px" }}>
        <div style={{ textAlign: "center", marginBottom: 16 }}>
          <div style={{ height: 2, width: 60, background: "var(--jt-red)", margin: "0 auto 10px" }}></div>
          <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 22, margin: 0, color: "var(--jt-navy-900)", letterSpacing: "0.01em" }}>
            Warranty Certificate
          </h2>
          <div style={{ marginTop: 4, color: "var(--jt-red)", fontWeight: 500, letterSpacing: "0.04em", fontSize: 12 }}>
            QNAP Advance Replacement Services
          </div>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 14 }}>
          <CertBox label="Certificate no." value={r.arsNo || r.id} mono />
          <CertBox label="Register date" value={window.fmtDate(r.registerDate)} />
        </div>

        <CertTable
          headers={["Warranty package", "Issue date", "Expire date"]}
          rows={[[r.warranty.package, window.fmtDate(r.warranty.start), window.fmtDate(r.warranty.end)]]}
          monoCols={[0]}
        />

        <CertSection title="Customer Information">
          <CertGrid>
            <CertField label="Company name" value={r.customer.company} span={2} />
            <CertField label="Company Address" value={`${r.customer.address}, ${r.customer.province} ${r.customer.zip}`} span={2} />
            <CertField label="Contact person" value={r.customer.contact} />
            <CertField label="Tel." value={r.customer.tel1} />
            <CertField label="Email" value={r.customer.email1} span={2} />
            {r.customer.email2 && <CertField label="Email 2" value={r.customer.email2} span={2} />}
          </CertGrid>
        </CertSection>

        <CertSection title="Product and Services Description">
          <CertGrid>
            <CertField label="Product" value={`${r.product.brand} NAS`} />
            <CertField label="Model" value={r.product.model} mono />
            <CertField label="Serial no." value={r.product.serial} mono />
            <CertField label="Warranty period" value={`${r.warranty.years} Yrs (${r.warranty.zone})`} />
            <CertField label="Installation Location" value={r.installationLocation} span={2} />
          </CertGrid>
        </CertSection>

        <CertSection title="Helpdesk Contact">
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18, fontSize: 12, color: "var(--text)" }}>
            <div>
              <div><strong>โทรศัพท์:</strong> 02-001-4902</div>
              <div><strong>Email:</strong> support@helpdesk.in.th</div>
            </div>
            <div>
              <div>วันจันทร์ – วันศุกร์ &nbsp;9.00 – 17.00</div>
              <div>วันเสาร์ – วันอาทิตย์ &nbsp;10.00 – 15.00</div>
              <div style={{ marginTop: 4, color: "var(--jt-red)", fontWeight: 600 }}>ให้บริการทุกวัน (24×7)</div>
            </div>
          </div>
        </CertSection>

        {/* Footer */}
        <div style={{ marginTop: 16, paddingTop: 10, borderTop: "1px solid var(--border)", textAlign: "center", color: "var(--text-soft)", fontSize: 10 }}>
          -- 1 of 1 -- &nbsp;•&nbsp; Generated by ARS Service Management on {new Date().toISOString().slice(0,10)}
        </div>
      </div>
    </div>
  );
}

function CertBox({ label, value, mono }) {
  return (
    <div style={{ background: "var(--surface-2)", border: "1px solid var(--border)", padding: "10px 14px", borderRadius: 4 }}>
      <div style={{ fontSize: 10, textTransform: "uppercase", letterSpacing: "0.08em", color: "var(--text-muted)", fontWeight: 600 }}>{label}</div>
      <div className={mono ? "mono" : ""} style={{ fontSize: 14, fontWeight: 600, marginTop: 2 }}>{value}</div>
    </div>
  );
}

function CertSection({ title, children }) {
  return (
    <div style={{ marginTop: 14 }}>
      <div style={{ background: "var(--jt-navy-800)", color: "#fff", padding: "6px 12px", fontFamily: "var(--font-display)", fontWeight: 500, fontSize: 11, letterSpacing: "0.04em", textTransform: "uppercase" }}>
        {title}
      </div>
      <div style={{ border: "1px solid var(--border)", borderTop: 0, padding: "8px 12px" }}>{children}</div>
    </div>
  );
}

function CertGrid({ children }) {
  return <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "10px 18px" }}>{children}</div>;
}

function CertField({ label, value, span, mono }) {
  return (
    <div style={{ gridColumn: span === 2 ? "span 2" : undefined, display: "flex", gap: 12 }}>
      <div style={{ fontSize: 11, color: "var(--text-muted)", minWidth: 110 }}>{label}</div>
      <div className={mono ? "mono" : ""} style={{ fontSize: 12.5, fontWeight: 500 }}>{value}</div>
    </div>
  );
}

function CertTable({ headers, rows, monoCols = [] }) {
  return (
    <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12.5 }}>
      <thead>
        <tr style={{ background: "var(--jt-navy-50)" }}>
          {headers.map(h => <th key={h} style={{ textAlign: "left", padding: "8px 12px", borderBottom: "1px solid var(--border)", fontWeight: 600 }}>{h}</th>)}
        </tr>
      </thead>
      <tbody>
        {rows.map((row, i) => (
          <tr key={i}>
            {row.map((c, j) => <td key={j} className={monoCols.includes(j) ? "mono" : ""} style={{ padding: "10px 12px", borderBottom: "1px solid var(--border)" }}>{c}</td>)}
          </tr>
        ))}
      </tbody>
    </table>
  );
}

window.CertificatesScreen = CertificatesScreen;
