/* Final CMR — clean, print-accurate 24-box rendering */

const FinalView = ({ data, onBack, onPrint }) => {
  const f = data.heroCase.fields;
  return (
    <div className="page" style={{maxWidth:1180}}>
      <header>
        <button className="icon-btn" onClick={onBack} title="Retour"><Icon name="arrow" size={14} style={{transform:"rotate(180deg)"}}/></button>
        <div>
          <h1>CMR-2026-0419 — Lettre de voiture</h1>
          <div className="sub">Validé le 22 mai 2026 à 11:42 par H. Bennani · prête à imprimer</div>
        </div>
        <div style={{marginLeft:"auto", display:"flex", gap:8}}>
          <StatusBadge status="approved"/>
          <button className="btn"><Icon name="mail" size={14}/> Renvoyer par email</button>
          <button className="btn" onClick={() => window.print()}><Icon name="print" size={14}/> Imprimer</button>
          <a className="btn primary" href={window.CN.api.pdfUrl(data.heroCase.ref)}
             download={`${data.heroCase.ref}.pdf`} onClick={onPrint}
             style={{textDecoration:"none"}}>
            <Icon name="download" size={14}/> Exporter PDF
          </a>
        </div>
      </header>

      <div className="cmr-sheet">
        {/* Header band */}
        <div className="cmr-head">
          <div style={{
            width:36, height:36, background:"var(--ink)",
            color:"#fff", display:"grid", placeItems:"center", fontWeight:700, fontSize:12,
            letterSpacing:"0.05em"
          }}>CMR</div>
          <div>
            <div className="title">LETTRE DE VOITURE INTERNATIONALE</div>
            <div className="sub">Convention relative au contrat de transport international de marchandises par route — Genève, 19 mai 1956</div>
          </div>
          <div className="lang">
            <div><b>FR</b> · Français</div>
            <div>EN · English</div>
            <div>AR · العربية</div>
          </div>
        </div>

        {/* Reference strip */}
        <div style={{display:"flex", justifyContent:"space-between", padding:"6px 14px", borderBottom:"1px solid #888", fontSize:10, fontFamily:"var(--font-mono)", color:"#444"}}>
          <span>N° : CMR-2026-0419</span>
          <span>Émis le 22/05/2026 — Casablanca, Maroc</span>
          <span>Original · Expéditeur</span>
        </div>

        <div className="cmr-grid">
          <Cell n="1" l="Expéditeur (nom, adresse, pays) — Sender">{f.sender.value}</Cell>
          <Cell n="16" l="Transporteur (nom, adresse, pays) — Carrier">{f.carrier.value}</Cell>

          <Cell n="2" l="Destinataire (nom, adresse, pays) — Consignee">{f.consignee.value}</Cell>
          <Cell n="17" l="Transporteurs successifs — Successive carriers"><em style={{color:"#888"}}>Aucun</em></Cell>

          <Cell n="3" l="Lieu prévu pour la livraison — Place of delivery">{f.placeOfDelivery.value}</Cell>
          <Cell n="18" l="Réservations du transporteur — Carrier's reservations">{f.reservations.value}</Cell>

          <Cell n="4" l="Lieu et date de la prise en charge — Place & date of taking over">
            {f.placeOfTaking.value}<br/>
            <span style={{fontFamily:"var(--font-mono)", fontSize:10.5}}>{f.dateOfTaking.value}</span>
          </Cell>
          <Cell n="19" l="Conventions particulières — Special agreements">{f.specialAgreements.value}</Cell>

          <Cell n="5" l="Documents annexés — Documents attached">{f.attachedDocs.value}</Cell>

          {/* Box 20 — payment table */}
          <div className="cmr-cell" style={{padding:0}}>
            <div className="n" style={{padding:"6px 8px 0"}}>20</div>
            <div className="l" style={{padding:"0 8px 4px"}}>À payer par — To be paid by</div>
            <table style={{width:"100%", fontSize:10, borderCollapse:"collapse"}}>
              <thead>
                <tr style={{background:"#f3f0e7"}}>
                  <th style={{padding:"3px 6px", borderTop:"1px solid #444", borderBottom:"1px solid #444", textAlign:"left"}}></th>
                  <th style={{padding:"3px 6px", borderTop:"1px solid #444", borderBottom:"1px solid #444", textAlign:"right"}}>Expéditeur</th>
                  <th style={{padding:"3px 6px", borderTop:"1px solid #444", borderBottom:"1px solid #444", textAlign:"right"}}>Destinataire</th>
                </tr>
              </thead>
              <tbody>
                {data.heroCase.charges.map((c, i) => (
                  <tr key={i}>
                    <td style={{padding:"2px 6px", borderBottom:"1px solid #ccc", fontWeight:c.bold?600:400}}>{c.label}</td>
                    <td style={{padding:"2px 6px", borderBottom:"1px solid #ccc", textAlign:"right", fontFamily:"var(--font-mono)", fontWeight:c.bold?600:400}}>{c.sender}</td>
                    <td style={{padding:"2px 6px", borderBottom:"1px solid #ccc", textAlign:"right", fontFamily:"var(--font-mono)", fontWeight:c.bold?600:400}}>{c.consignee}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          {/* Goods — full row spanning both columns, boxes 6–12 */}
          <div className="cmr-cell full" style={{padding:0}}>
            <div style={{padding:"6px 8px"}}>
              <div style={{display:"flex", gap:14, fontSize:9.5, color:"#444", fontFamily:"var(--font-mono)"}}>
                <span><b>6</b> Marques</span>
                <span><b>7</b> Nombre de colis</span>
                <span><b>8</b> Emballage</span>
                <span><b>9</b> Nature</span>
                <span><b>10</b> SH</span>
                <span><b>11</b> Poids brut (kg)</span>
                <span><b>12</b> Volume (m³)</span>
              </div>
            </div>
            <table style={{width:"100%", fontSize:10.5, borderCollapse:"collapse", borderTop:"1px solid #444"}}>
              <thead>
                <tr style={{background:"#f3f0e7"}}>
                  <th style={{padding:"4px 8px", borderBottom:"1px solid #444", textAlign:"left", width:"15%"}}>Marques (6)</th>
                  <th style={{padding:"4px 8px", borderBottom:"1px solid #444", textAlign:"left", width:"7%"}}>Colis (7)</th>
                  <th style={{padding:"4px 8px", borderBottom:"1px solid #444", textAlign:"left", width:"13%"}}>Emballage (8)</th>
                  <th style={{padding:"4px 8px", borderBottom:"1px solid #444", textAlign:"left"}}>Nature de la marchandise (9)</th>
                  <th style={{padding:"4px 8px", borderBottom:"1px solid #444", textAlign:"left", width:"10%"}}>SH (10)</th>
                  <th style={{padding:"4px 8px", borderBottom:"1px solid #444", textAlign:"right", width:"10%"}}>kg (11)</th>
                  <th style={{padding:"4px 8px", borderBottom:"1px solid #444", textAlign:"right", width:"8%"}}>m³ (12)</th>
                </tr>
              </thead>
              <tbody>
                {f.goods.map((g) => (
                  <tr key={g.id}>
                    <td style={{padding:"5px 8px", borderBottom:"1px solid #bbb", fontFamily:"var(--font-mono)"}}>{g.marks}</td>
                    <td style={{padding:"5px 8px", borderBottom:"1px solid #bbb"}}>{g.packages}</td>
                    <td style={{padding:"5px 8px", borderBottom:"1px solid #bbb"}}>{g.packing}</td>
                    <td style={{padding:"5px 8px", borderBottom:"1px solid #bbb"}}>{g.nature}</td>
                    <td style={{padding:"5px 8px", borderBottom:"1px solid #bbb", fontFamily:"var(--font-mono)"}}>{g.hs}</td>
                    <td style={{padding:"5px 8px", borderBottom:"1px solid #bbb", textAlign:"right", fontFamily:"var(--font-mono)"}}>{g.weight}</td>
                    <td style={{padding:"5px 8px", borderBottom:"1px solid #bbb", textAlign:"right", fontFamily:"var(--font-mono)"}}>{g.volume}</td>
                  </tr>
                ))}
                {(() => {
                  const tot = goodsTotals(f.goods);
                  const fr = (n) => n.toLocaleString("fr-FR", { maximumFractionDigits: 2 });
                  return (
                    <tr style={{background:"#fafaf3"}}>
                      <td colSpan="4" style={{padding:"5px 8px", textAlign:"right", fontWeight:600}}>Total</td>
                      <td style={{padding:"5px 8px"}}></td>
                      <td style={{padding:"5px 8px", textAlign:"right", fontFamily:"var(--font-mono)", fontWeight:600}}>{fr(tot.weight)}</td>
                      <td style={{padding:"5px 8px", textAlign:"right", fontFamily:"var(--font-mono)", fontWeight:600}}>{fr(tot.volume)}</td>
                    </tr>
                  );
                })()}
              </tbody>
            </table>
          </div>

          <Cell n="13" l="Instructions de l'expéditeur — Sender's instructions">{f.senderInstructions.value}</Cell>
          <Cell n="14" l="Prix de transport — Carriage payment">{f.payment.value}</Cell>

          <Cell n="15" l="Remboursement — Cash on delivery"><em style={{color:"#888"}}>—</em></Cell>
          <Cell n="21" l="Établi à — Drawn up at">
            {f.placeOfIssue.value}, le <span style={{fontFamily:"var(--font-mono)"}}>{f.dateOfIssue.value}</span>
          </Cell>
        </div>

        {/* Signatures band */}
        <div style={{display:"grid", gridTemplateColumns:"1fr 1fr 1fr", borderTop:"2px solid #111"}}>
          {[
            {n:"22", l:"Signature & cachet de l'expéditeur"},
            {n:"23", l:"Signature & cachet du transporteur"},
            {n:"24", l:"Signature & cachet du destinataire"},
          ].map((s, i) => (
            <div key={i} style={{
              padding:"12px 14px 30px",
              borderLeft: i===0?"0":"1px solid #444",
              minHeight: 110,
              position:"relative",
            }}>
              <div style={{fontFamily:"var(--font-mono)", fontSize:10, fontWeight:700}}>{s.n}</div>
              <div style={{fontSize:9.5, color:"#444"}}>{s.l}</div>
              <div style={{position:"absolute", left:14, right:14, bottom:8, fontSize:9, color:"#888", borderTop:"1px solid #aaa", paddingTop:4}}>
                Lieu, date, nom et signature
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Audit trail */}
      <div style={{marginTop:24, display:"grid", gridTemplateColumns:"1fr 1fr", gap:16}}>
        <div className="card">
          <div className="card-head">
            <Icon name="history" size={14}/>
            <h3>Journal d'activité</h3>
          </div>
          <ul style={{margin:0, padding:0, listStyle:"none"}}>
            {[
              ["11:42", "H. Bennani", "Validé et exporté le CMR final"],
              ["11:38", "H. Bennani", "Modifié 2 champs (réservations · poids ligne 3)"],
              ["11:35", "H. Bennani", "Ouvert le brouillon pour vérification"],
              ["09:14", "Système",    "Extraction terminée — 22/27 champs en haute confiance"],
              ["09:12", "Email entrant", "Email reçu de logistique@soremed.ma"],
            ].map((e, i) => (
              <li key={i} style={{display:"grid", gridTemplateColumns:"60px 130px 1fr", padding:"9px 14px", borderTop:i===0?"0":"1px solid var(--hairline)", fontSize:12.5}}>
                <span className="mono" style={{color:"var(--muted)"}}>{e[0]}</span>
                <span style={{color:"var(--ink-2)", fontWeight:500}}>{e[1]}</span>
                <span style={{color:"var(--muted)"}}>{e[2]}</span>
              </li>
            ))}
          </ul>
        </div>
        <div className="card">
          <div className="card-head">
            <Icon name="folder" size={14}/>
            <h3>Pièces du dossier</h3>
          </div>
          <ul style={{margin:0, padding:0, listStyle:"none"}}>
            {data.heroCase.docs.map((d) => (
              <li key={d.id} style={{display:"flex", alignItems:"center", gap:10, padding:"9px 14px", borderTop:"1px solid var(--hairline)", fontSize:12.5}}>
                <Icon name={d.kind === "email" ? "mail" : d.kind === "image" ? "image" : "pdf"} size={14} style={{color:"var(--muted)"}}/>
                <span style={{flex:1}}>{d.label}</span>
                <button className="btn sm ghost"><Icon name="eye" size={12}/></button>
                <button className="btn sm ghost"><Icon name="download" size={12}/></button>
              </li>
            ))}
          </ul>
        </div>
      </div>
    </div>
  );
};

const Cell = ({ n, l, children }) => (
  <div className="cmr-cell">
    <div className="n">{n}</div>
    <div className="l">{l}</div>
    <div className="v">{children}</div>
  </div>
);

window.FinalView = FinalView;
