// ─── Kundenbewertungen (AudioFlow review site → app) ──────────────────────
// Records match the review site's shape 1:1:
//   { id, ts, ratings:{sound,condition,advice,handover,price,overall}, average, comment, lang }
// Stored in the app under 'rf-reviews'. The review site writes 'audioflow_reviews_v1';
// when both are served from the same origin we auto-merge those in by id.
const REVIEW_QIDS = ['sound', 'condition', 'advice', 'handover', 'price', 'overall'];
const REVIEW_TITLES = {
  sound: 'Klangqualität',
  condition: 'Zustand der Geräte',
  advice: 'Kommunikation',
  handover: 'Lieferung & Abholung',
  price: 'Preis-Leistung',
  overall: 'Gesamteindruck',
};
const REVIEW_SITE_KEY = 'audioflow_reviews_v1';

// Merge helper — dedupes by id, keeps chronological order.
function mergeReviews(a = [], b = []) {
  const dismissed = loadDismissedReviews();
  const map = new Map();
  [...a, ...b].forEach((r) => { if (r && r.id != null && !dismissed.has(String(r.id))) map.set(String(r.id), r); });
  return [...map.values()].sort((x, y) => (x.ts || 0) - (y.ts || 0));
}
// Pull whatever the review site left in this browser (same-origin case).
function loadSiteReviews() {
  try { const raw = localStorage.getItem(REVIEW_SITE_KEY); return raw ? JSON.parse(raw) : []; }
  catch (e) { return []; }
}
// Permanently dismissed review ids — deleted reviews must never reappear on import/auto-merge.
// Server-gespeichert (RFDB), damit ein Löschen auf einem Gerät auf allen Geräten gilt.
const REVIEW_DISMISSED_KEY = 'rf-reviews-dismissed';
function loadDismissedReviews() {
  const v = window.RFDB ? window.RFDB.get(REVIEW_DISMISSED_KEY) : undefined;
  return new Set(Array.isArray(v) ? v : []);
}
function addDismissedReview(id) {
  const s = loadDismissedReviews(); s.add(String(id));
  if (window.RFDB) window.RFDB.set(REVIEW_DISMISSED_KEY, [...s]).catch(() => {});
}
function reviewStars(n) {
  // returns 5 booleans for filled stars given a 0..5 value (rounded)
  const r = Math.round(n);
  return [1, 2, 3, 4, 5].map((i) => i <= r);
}
function StarRow({ value, size = 16 }) {
  return (
    <div style={{ display: 'flex', gap: 2 }}>
      {reviewStars(value).map((on, i) => (
        <svg key={i} viewBox="0 0 24 24" width={size} height={size} fill={on ? 'rgba(198,160,74,0.9)' : 'rgba(198,160,74,0.16)'}>
          <path d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"/>
        </svg>
      ))}
    </div>
  );
}

// ─── Overview card for the home tab ───────────────────────────────────────
function ReviewsCard({ reviews = [], onOpen }) {
  const t = useTheme();
  const count = reviews.length;
  const avg = count ? reviews.reduce((a, r) => a + (Number(r.average) || 0), 0) / count : 0;
  const fmt = (n) => (Math.round(n * 10) / 10).toFixed(1).replace('.', ',');
  return (
    <Pressable onClick={onOpen} scale={0.98}>
      <div style={{ background: t.card, border: `0.5px solid ${t.sep}`, borderRadius: 18, padding: '18px 20px', boxShadow: t.shadowCard, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 14 }}>
        <div style={{ minWidth: 0 }}>
          <div style={{ fontSize: 12, color: t.textSec, fontWeight: 600 }}>Kundenbewertungen</div>
          {count ? (
            <>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 4 }}>
                <span style={{ fontSize: 26, fontWeight: 700, color: t.text, letterSpacing: -0.6, fontVariantNumeric: 'tabular-nums' }}>{fmt(avg)}</span>
                <span style={{ fontSize: 13, fontWeight: 600, color: t.textSec }}>/ 5</span>
              </div>
              <div style={{ marginTop: 5 }}><StarRow value={avg}/></div>
              <div style={{ fontSize: 11.5, color: t.textSec, marginTop: 5 }}>{count} {count === 1 ? 'Bewertung' : 'Bewertungen'}</div>
            </>
          ) : (
            <div style={{ fontSize: 13.5, color: t.text, fontWeight: 600, marginTop: 4 }}>Noch keine Bewertungen</div>
          )}
        </div>
        <Icon d="M9 18l6-6-6-6" color={t.textSec} size={16} sw={2}/>
      </div>
    </Pressable>
  );
}

// ─── Detail sheet: per-category analysis + individual submissions + import ──
function ReviewsSheet({ open, onClose, reviews = [], setReviews, toast }) {
  const t = useTheme();
  const fileRef = React.useRef(null);
  const count = reviews.length;
  const overall = count ? reviews.reduce((a, r) => a + (Number(r.average) || 0), 0) / count : 0;
  const fmt = (n) => (Math.round(n * 10) / 10).toFixed(1).replace('.', ',');

  const breakdown = REVIEW_QIDS.map((id) => {
    const vals = reviews.map((r) => r.ratings && r.ratings[id]).filter((v) => typeof v === 'number');
    const avg = vals.length ? vals.reduce((a, b) => a + b, 0) / vals.length : 0;
    return { id, title: REVIEW_TITLES[id], avg, has: vals.length > 0 };
  });

  const importFromBrowser = () => {
    const site = loadSiteReviews();
    if (!site.length) { toast && toast('Keine Bewertungen in diesem Browser gefunden'); return; }
    const before = reviews.length;
    const merged = mergeReviews(reviews, site);
    setReviews(merged);
    toast && toast(`${merged.length - before} neue Bewertung(en) übernommen`);
  };
  const importFromFile = (e) => {
    const file = e.target.files && e.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = () => {
      try {
        const data = JSON.parse(reader.result);
        const list = Array.isArray(data) ? data : (data.reviews || []);
        const before = reviews.length;
        const merged = mergeReviews(reviews, list);
        setReviews(merged);
        toast && toast(`${merged.length - before} neue Bewertung(en) importiert`);
      } catch (err) { toast && toast('Datei konnte nicht gelesen werden'); }
    };
    reader.readAsText(file);
    e.target.value = '';
  };

  const deleteReview = (id) => {
    if (id != null) addDismissedReview(id);
    setReviews((prev) => prev.filter((r) => String(r.id) !== String(id)));
    toast && toast('Bewertung gelöscht');
  };

  return (
    <Sheet open={open} onClose={onClose} maxHeight="90%">
      <div style={{ padding: '4px 20px 28px' }}>
        <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 12, marginBottom: 4 }}>
          <div>
            <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: 1.2, textTransform: 'uppercase', color: t.textSec }}>Intern · Übersicht</div>
            <div style={{ fontSize: 24, fontWeight: 700, color: t.text, letterSpacing: -0.5, marginTop: 3 }}>Bewertungen</div>
          </div>
        </div>

        {/* Summary */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginTop: 14 }}>
          <div style={{ background: t.cardAlt, borderRadius: 16, padding: '16px 18px' }}>
            <div style={{ fontSize: 11.5, color: t.textSec, marginBottom: 6 }}>Gesamt</div>
            <div style={{ fontSize: 30, fontWeight: 700, color: t.text, letterSpacing: -0.6, lineHeight: 1, fontVariantNumeric: 'tabular-nums' }}>{count}</div>
          </div>
          <div style={{ background: t.cardAlt, borderRadius: 16, padding: '16px 18px' }}>
            <div style={{ fontSize: 11.5, color: t.textSec, marginBottom: 6 }}>Durchschnitt</div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
              <span style={{ fontSize: 30, fontWeight: 700, color: t.text, letterSpacing: -0.6, lineHeight: 1, fontVariantNumeric: 'tabular-nums' }}>{count ? fmt(overall) : '–'}</span>
              <span style={{ fontSize: 14, fontWeight: 600, color: t.textSec }}>/ 5</span>
            </div>
            <div style={{ marginTop: 8 }}><StarRow value={overall} size={15}/></div>
          </div>
        </div>

        {/* Per-category breakdown */}
        <div style={{ fontSize: 11, color: t.textSec, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.5, marginTop: 22, marginBottom: 10 }}>Auswertung pro Kategorie</div>
        <div style={{ background: t.card, border: `0.5px solid ${t.sep}`, borderRadius: 16, padding: '18px 18px', display: 'flex', flexDirection: 'column', gap: 16 }}>
          {breakdown.map((b) => (
            <div key={b.id} style={{ display: 'grid', gridTemplateColumns: '1fr auto', gap: '6px 12px', alignItems: 'center' }}>
              <span style={{ fontSize: 13.5, fontWeight: 600, color: t.text }}>{b.title}</span>
              <span style={{ fontSize: 13.5, fontWeight: 700, color: t.text, fontVariantNumeric: 'tabular-nums' }}>{b.has ? fmt(b.avg) : '–'}</span>
              <div style={{ gridColumn: '1 / -1', height: 8, borderRadius: 999, background: t.chip, overflow: 'hidden' }}>
                <div style={{ height: '100%', width: (b.avg / 5 * 100) + '%', background: t.text, borderRadius: 999, transition: 'width .4s ease' }}/>
              </div>
            </div>
          ))}
        </div>

        {/* Individual submissions */}
        <div style={{ fontSize: 11, color: t.textSec, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.5, marginTop: 22, marginBottom: 10 }}>Einzelne Bewertungen</div>
        {count === 0 ? (
          <div style={{ background: t.card, border: `1px dashed ${t.sep}`, borderRadius: 16, padding: '32px 20px', textAlign: 'center', color: t.textSec, fontSize: 13 }}>
            Noch keine Bewertungen. Über „Import" unten übernehmen.
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {reviews.slice().reverse().map((r) => (
              <div key={r.id} style={{ background: t.card, border: `0.5px solid ${t.sep}`, borderRadius: 16, padding: '14px 16px', display: 'flex', flexDirection: 'column', gap: 10 }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, flexWrap: 'wrap' }}>
                  <span style={{ fontSize: 12, color: t.textSec }}>{new Date(r.ts).toLocaleString('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' })}</span>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '5px 12px', borderRadius: 999, background: t.cardAlt, fontWeight: 700, fontSize: 13 }}>{fmt(Number(r.average) || 0)} / 5</span>
                    <Pressable onClick={() => deleteReview(r.id)} scale={0.85}>
                      <div style={{ width: 30, height: 30, borderRadius: 15, background: t.cardAlt, display: 'flex', alignItems: 'center', justifyContent: 'center' }} title="Bewertung löschen">
                        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke={t.red || '#FF3B30'} strokeWidth="2.1" strokeLinecap="round" strokeLinejoin="round"><path d="M3 6h18M8 6V4a2 2 0 012-2h4a2 2 0 012 2v2m2 0v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6"/></svg>
                      </div>
                    </Pressable>
                  </div>
                </div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7 }}>
                  {REVIEW_QIDS.map((id) => (
                    <span key={id} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '5px 11px', borderRadius: 999, border: `1px solid ${t.sep}`, fontSize: 11.5, color: t.textSec }}>
                      {REVIEW_TITLES[id]} <strong style={{ fontWeight: 700, color: t.text }}>{(r.ratings && r.ratings[id]) || '–'}</strong>
                    </span>
                  ))}
                </div>
                {r.comment ? (
                  <p style={{ margin: 0, padding: '10px 12px', background: t.cardAlt, borderRadius: 10, fontSize: 12.5, color: t.text, lineHeight: 1.5 }}>{r.comment}</p>
                ) : null}
              </div>
            ))}
          </div>
        )}

        {/* Import controls */}
        <div style={{ fontSize: 11, color: t.textSec, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.5, marginTop: 22, marginBottom: 10 }}>Bewertungen übernehmen</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          <Pressable onClick={importFromBrowser} scale={0.98}>
            <div style={{ padding: '13px 16px', borderRadius: 12, background: t.chip, color: t.text, fontSize: 13.5, fontWeight: 600, textAlign: 'center' }}>Aus diesem Browser übernehmen</div>
          </Pressable>
          <Pressable onClick={() => fileRef.current && fileRef.current.click()} scale={0.98}>
            <div style={{ padding: '13px 16px', borderRadius: 12, background: t.solidBg, color: t.solidFg, fontSize: 13.5, fontWeight: 700, textAlign: 'center' }}>JSON-Export importieren</div>
          </Pressable>
          <input ref={fileRef} type="file" accept="application/json,.json" onChange={importFromFile} style={{ display: 'none' }}/>
        </div>
        <p style={{ fontSize: 11.5, color: t.textSec, lineHeight: 1.6, marginTop: 12 }}>
          Die Bewertungsseite speichert jede Bewertung. Läuft sie auf derselben Domain wie diese App, werden neue Bewertungen automatisch übernommen — sonst per JSON-Export/-Import oder über eine zentrale Datenbank-Anbindung.
        </p>
      </div>
    </Sheet>
  );
}

Object.assign(window, { ReviewsCard, ReviewsSheet, REVIEW_QIDS, REVIEW_TITLES, mergeReviews, loadSiteReviews, loadDismissedReviews });
