// Order detail page — hero, timeline, real photos, sidebar

const { useState: useStateDetail, useEffect: useEffectDetail, useRef } = React;

function TimelineItem({ step, state, timestamp }) {
  return (
    <div className={`timeline-item ${state}`}>
      <div className="timeline-dot">
        {state === 'completed' && <window.Icon.Check />}
      </div>
      <div className="timeline-content">
        <div className="timeline-title">{step.label}</div>
        {timestamp && <div className="timeline-meta">{window.formatDate(timestamp)}</div>}
        {state === 'active' && !timestamp && <div className="timeline-meta">Läuft gerade …</div>}
      </div>
    </div>
  );
}

function PhotoGrid({ sessionId, token }) {
  const [photos, setPhotos] = useStateDetail([]);
  const [loading, setLoading] = useStateDetail(false);

  useEffectDetail(() => {
    if (!sessionId) { setPhotos([]); return; }
    let cancelled = false;
    const load = async () => {
      setLoading(true);
      let data;
      try { data = await portalApi('/api/portal-storage', { action: 'photos', token }, { auth: true }); }
      catch (_) { data = null; }
      if (cancelled) return;
      if (!data) { setLoading(false); return; }
      const urls = (data.photos || []).map(photo => photo.url);
      if (!cancelled) {
        setPhotos(urls.filter(Boolean));
        setLoading(false);
      }
    };
    load();
    return () => { cancelled = true; };
  }, [sessionId, token]);

  if (!sessionId) {
    return (
      <div className="photo-empty">
        <window.Icon.Camera />
        <div>Noch keine Fotos hochgeladen.</div>
        <div style={{ fontSize: '0.82rem', marginTop: '0.25rem', opacity: 0.75 }}>
          Die Familie wurde per E-Mail eingeladen.
        </div>
      </div>
    );
  }

  if (loading) {
    return <div className="photo-empty" style={{ opacity: 0.6 }}>Fotos werden geladen …</div>;
  }

  if (photos.length === 0) {
    return (
      <div className="photo-empty">
        <window.Icon.Camera />
        <div>Noch keine Fotos hochgeladen.</div>
      </div>
    );
  }

  return (
    <div className="photo-grid">
      {photos.slice(0, 18).map((url, i) => (
        <div key={i} className="photo-thumb">
          <img
            src={url}
            alt={`Foto ${i + 1}`}
            style={{ width: '100%', height: '100%', objectFit: 'cover', borderRadius: '4px' }}
            loading="lazy"
          />
        </div>
      ))}
      {photos.length > 18 && (
        <div className="photo-thumb">
          <div className="photo-placeholder" style={{ '--bg1': '#5D4E3A', '--bg2': '#3D3426', color: '#fff', fontWeight: 600 }}>
            +{photos.length - 18}
          </div>
        </div>
      )}
    </div>
  );
}

function NoteWidget({ orderId, initialNote, adminNote }) {
  const [note, setNote] = useStateDetail(initialNote || '');
  const [saving, setSaving] = useStateDetail(false);
  const [saved, setSaved] = useStateDetail(false);

  const save = async () => {
    setSaving(true);
    await window.sb.from('funeral_orders').update({ internal_note: note }).eq('id', orderId);
    setSaving(false);
    setSaved(true);
    setTimeout(() => setSaved(false), 2000);
  };

  return (
    <div className="side-card">
      <h4>Interne Notiz</h4>
      <textarea
        className="form-textarea"
        rows={3}
        placeholder="Notizen, Termine, Sonderwünsche …"
        value={note}
        onChange={e => setNote(e.target.value)}
        style={{ marginBottom: '0.5rem' }}
      />
      <button
        className="btn btn-secondary"
        style={{ width: '100%', justifyContent: 'center' }}
        onClick={save}
        disabled={saving}
      >
        {saved ? '✓ Gespeichert' : saving ? 'Wird gespeichert …' : 'Notiz speichern'}
      </button>

      {adminNote && (
        <div style={{ marginTop: '1rem', padding: '0.65rem 0.8rem', background: 'rgba(100,160,120,0.08)', border: '1px solid rgba(100,160,120,0.25)', borderRadius: '4px' }}>
          <div style={{ fontSize: '0.7rem', textTransform: 'uppercase', letterSpacing: '0.1em', color: 'var(--a-success)', marginBottom: '0.35rem', fontWeight: 600 }}>
            Antwort von Erinnerungsvideo
          </div>
          <div style={{ fontSize: '0.88rem', color: 'var(--a-ink)', whiteSpace: 'pre-wrap' }}>{adminNote}</div>
        </div>
      )}
    </div>
  );
}

function OrderDetail({ order, onBack, onShowQR, onResendEmail, onDelete, onDownload, onRefreshOrder }) {
  if (!order) return null;

  const badge = window.STATUS_BADGE[order.status] || { label: order.status, cls: '' };
  const currentIdx = window.statusIndex(order.status);
  const screenLabel = `02 Auftragsdetails — ${order.customerName}`;

  const stepTimestamps = {
    'created':    order.createdAt,
    'email-sent': order.emailSentAt,
    'uploading':  order.uploadStartedAt,
    'submitted':  order.uploadCompletedAt,
    'processing': order.uploadCompletedAt,
    'done':       order.videoReadyAt,
  };

  // Auto-refresh status every 30 s until done
  useEffectDetail(() => {
    if (order.status === 'done' || !onRefreshOrder) return;
    const iv = setInterval(() => onRefreshOrder(order.id), 30000);
    return () => clearInterval(iv);
  }, [order.id, order.status]);

  return (
    <main className="portal-body" data-screen-label={screenLabel}>
      <button className="back-nav" onClick={onBack}>
        <window.Icon.ArrowLeft /> Zurück zur Übersicht
      </button>

      <div className="detail-hero">
        <div className="order-avatar">{window.initials(order.customerName)}</div>
        <div className="hero-info">
          <h1>{order.customerName}</h1>
          {order.deceased && (
            <p style={{ color: 'var(--a-muted)', fontSize: '0.95rem', marginTop: '0.1rem' }}>
              Erinnerungsvideo für <strong style={{ color: 'var(--a-ink)', fontWeight: 600 }}>{order.deceased}</strong>
            </p>
          )}
          <div className="hero-meta">
            <span className="meta-item"><window.Icon.Calendar /> Erstellt am {window.formatDate(order.createdAt)}</span>
          </div>
          <div className="hero-badge-row">
            <span className={`badge ${badge.cls}`}>{badge.label}</span>
          </div>
        </div>
      </div>

      {order.status === 'done' && (
        <div className="video-ready">
          <div className="video-ready-icon"><window.Icon.Play /></div>
          <div className="video-ready-text">
            <strong>Erinnerungsvideo ist fertig</strong>
            <span>Bereit zur Übergabe an die Familie</span>
          </div>
          <button className="btn btn-download" onClick={() => onDownload(order)}>
            <window.Icon.Download /> Video herunterladen
          </button>
        </div>
      )}

      <div className="detail-grid">
        <div>
          <div className="detail-card">
            <h3>Status-Verlauf</h3>
            <div className="timeline">
              {window.STATUS_STEPS.map((step, i) => {
                let state = '';
                if (i < currentIdx) state = 'completed';
                else if (i === currentIdx) state = order.status === 'done' ? 'completed' : 'active';
                return (
                  <TimelineItem
                    key={step.key}
                    step={step}
                    state={state}
                    timestamp={state !== '' ? stepTimestamps[step.key] : null}
                  />
                );
              })}
            </div>
          </div>

          <div className="detail-card">
            <h3>Hochgeladene Fotos</h3>
            <PhotoGrid sessionId={order.sessionId} token={order.token} />
          </div>
        </div>

        <aside>
          <div className="side-card">
            <h4>Kontakt</h4>
            <div className="info-list">
              <div className="info-row">
                <span className="info-label">Name</span>
                <span className="info-value">{order.customerName}</span>
              </div>
              <div className="info-row">
                <span className="info-label">E-Mail</span>
                <span className="info-value">{order.email}</span>
              </div>
              {order.phone && (
                <div className="info-row">
                  <span className="info-label">Telefon</span>
                  <span className="info-value">{order.phone}</span>
                </div>
              )}
              {order.deceased && (
                <div className="info-row">
                  <span className="info-label">Verstorbene/r</span>
                  <span className="info-value">{order.deceased}</span>
                </div>
              )}
            </div>
          </div>

          <NoteWidget orderId={order.id} initialNote={order.note} adminNote={order.adminNote} />


          <div className="side-card">
            <h4>Aktionen</h4>
            <div className="side-actions">
              <button className="btn btn-secondary" onClick={() => onShowQR(order)}>
                <window.Icon.QR /> QR-Code anzeigen
              </button>
              <button className="btn btn-secondary" onClick={() => onResendEmail(order)}>
                <window.Icon.Mail /> E-Mail erneut senden
              </button>
              <button className="btn btn-danger" onClick={() => onDelete(order)}>
                <window.Icon.Trash /> Auftrag löschen
              </button>
            </div>
          </div>
        </aside>
      </div>
    </main>
  );
}

window.OrderDetail = OrderDetail;
