// score.jsx — BlocApp Score: rating bloc + raport public pentru cumpărători

// Compute building score (mock — production would aggregate real data)
window.computeBuildingScore = function() {
  // Components: financial health, compliance, transparency, arrears, infrastructure
  const totalArrears = Object.values(window.ARREARS_LEDGER || {}).flat().reduce((s, l) => s + (l.original - l.paid + l.penalty), 0);
  const compliantCount = (window.COMPLIANCE_ITEMS || []).filter(c => window.complianceStatus(c).state === 'valid' || window.complianceStatus(c).state === 'expiring').length;
  const compliantTotal = (window.COMPLIANCE_ITEMS || []).length;
  const fundLevel = (window.VAULT?.balance || 0);

  return {
    financial: { score: 4.5, label: 'Bun', detail: 'Fond reparații solid (28.4k RON)', max: 5, color: '#059669' },
    compliance: { score: 3.2, label: 'Atenție', detail: `${compliantCount}/${compliantTotal} verificări valide · 1 expirată`, max: 5, color: '#D97706' },
    transparency: { score: 5.0, label: 'Excelent', detail: 'Multi-sig + ANAF + audit complet', max: 5, color: '#059669' },
    arrears: { score: 3.8, label: 'Acceptabil', detail: `${Object.keys(window.ARREARS_LEDGER || {}).length} apt cu restanțe · 9.487 RON`, max: 5, color: '#D97706' },
    infrastructure: { score: 4.2, label: 'Bun', detail: 'Lift, hidrofor, acoperiș reparat 2025', max: 5, color: '#059669' },
    community: { score: 4.6, label: 'Bun', detail: 'AGA participare 73% · 5 sesizări rezolvate', max: 5, color: '#059669' },
    overall: 4.2,
    grade: 'B+',
  };
};

// Public history facts pentru cumpărător
window.BUILDING_FACTS = [
  { ts: '2025-08', icon: '🔨', text: 'Reparație acoperiș — infiltrații (4.200 RON)', positive: true },
  { ts: '2025-07', icon: '🧯', text: 'PSI extinctoare recertificare anuală', positive: true },
  { ts: '2025-04', icon: '🦟', text: 'Igienizare DSP semestrială', positive: true },
  { ts: '2024-12', icon: '🛗', text: 'Verificare ISCIR lift trecută', positive: true },
  { ts: '2024-10', icon: '👤', text: 'Schimbare administrator (AGA — 9 pentru, 3 împotrivă)', positive: true },
  { ts: '2024-08', icon: '🌡️', text: 'Modernizare instalație termică casa scării (12.500 RON)', positive: true },
  { ts: '2023-06', icon: '🎨', text: 'Reabilitare termică finalizată (320.000 RON · grant)', positive: true },
];

function ScoreScreen({ state, tr, lang }) {
  const score = window.computeBuildingScore();
  const [showShareModal, setShowShareModal] = React.useState(false);
  const toast = useToast();

  const gradeColor = score.overall >= 4.5 ? '#059669' : score.overall >= 3.5 ? '#D97706' : '#DC2626';

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 24, maxWidth: 1280 }}>
      <PageHeader
        title="BlocApp Score"
        subtitle="Reputație publică a scării — vizibilă pentru cumpărători, agenți imobiliari, autorități"
        right={<Button variant="primary" icon="download" onClick={() => setShowShareModal(true)}>Generează raport public</Button>}
      />

      {/* Why this exists */}
      <Card style={{ background: 'linear-gradient(135deg, #E0F2FE, #cae8f8)', border: '1px solid #0EA5E9' }}>
        <div style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
          <div style={{ width: 44, height: 44, borderRadius: 12, background: '#0EA5E9', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 22, flexShrink: 0 }}>⭐</div>
          <div style={{ flex: 1, fontSize: 13.5, color: '#0C4A6E', lineHeight: 1.55 }}>
            <b>Cum funcționează:</b> Un cumpărător care vrea Ap.5 nu are cum să afle astăzi: există restanțe? Câte avarii a avut blocul? Verificările sunt la zi? Fondul de reparații e gol? <b>BlocApp Score</b> agregă toate datele și generează un raport public verificabil pe care vânzătorul îl atașează la anunțul OLX/Imobiliare.ro. Câștig pentru cumpărător, vânzător, agent — și pentru noi (canal nou de distribuție).
          </div>
        </div>
      </Card>

      {/* Big score card */}
      <Card style={{
        background: 'linear-gradient(135deg, #1F4738, #2d6a52)',
        color: '#fff',
        padding: 32,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 32 }}>
          {/* Letter grade */}
          <div style={{
            width: 140, height: 140, borderRadius: 24,
            background: 'rgba(255,255,255,0.12)',
            border: '2px solid rgba(255,255,255,0.2)',
            display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
            flexShrink: 0,
          }}>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 64, fontWeight: 700, lineHeight: 1, letterSpacing: '-0.02em' }}>{score.grade}</div>
            <div style={{ fontSize: 11, opacity: 0.7, textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 600, marginTop: 4 }}>Scor</div>
          </div>

          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 11, opacity: 0.7, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 6 }}>{window.BUILDING.name}</div>
            <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 32, fontWeight: 600, margin: 0, letterSpacing: '-0.01em', lineHeight: 1.1 }}>
              <Ticker value={score.overall} decimals={1} /> <span style={{ fontSize: 18, opacity: 0.7 }}>/ 5.0</span>
            </h2>
            <div style={{ marginTop: 8, display: 'flex', gap: 4 }}>
              {[1,2,3,4,5].map(i => (
                <span key={i} style={{ fontSize: 20, color: i <= Math.round(score.overall) ? '#FCD34D' : 'rgba(255,255,255,0.25)' }}>★</span>
              ))}
            </div>
            <div style={{ marginTop: 10, fontSize: 13, opacity: 0.85, lineHeight: 1.5 }}>
              Bloc bine întreținut · transparență radicală · 1 punct slab (verificări restante)
            </div>
          </div>

          {/* Quick facts */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, fontSize: 12, opacity: 0.95 }}>
            <ScoreFact icon="✓" text="Plată la zi 11/12 luni" />
            <ScoreFact icon="✓" text="Fond reparații 28.4k RON" />
            <ScoreFact icon="✓" text="Reabilitare termică 2023" />
            <ScoreFact icon="⚠" text="DSP igienizare expirată" warn />
            <ScoreFact icon="✓" text="0 procese în derulare" />
          </div>
        </div>
      </Card>

      {/* 6 dimensions */}
      <div>
        <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 600, color: 'var(--ink)', margin: '0 0 14px' }}>Detaliu pe dimensiuni</h3>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 'var(--gap)' }}>
          <ScoreDimension label="Sănătate financiară"  icon="💰" data={score.financial} />
          <ScoreDimension label="Verificări obligatorii" icon="✅" data={score.compliance} />
          <ScoreDimension label="Transparență"          icon="🔍" data={score.transparency} />
          <ScoreDimension label="Restanțe"               icon="⏳" data={score.arrears} />
          <ScoreDimension label="Infrastructură"         icon="🏗️" data={score.infrastructure} />
          <ScoreDimension label="Comunitate"             icon="🤝" data={score.community} />
        </div>
      </div>

      {/* Timeline */}
      <Card>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 18 }}>
          <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 600, color: 'var(--ink)', margin: 0 }}>Istoric public bloc</h3>
          <span style={{ fontSize: 12, color: 'var(--muted)' }}>Ce vede un cumpărător</span>
        </div>
        <div style={{ position: 'relative', paddingLeft: 28 }}>
          <div style={{ position: 'absolute', left: 13, top: 6, bottom: 6, width: 2, background: 'var(--border)' }} />
          {window.BUILDING_FACTS.map((f, i) => (
            <div key={i} style={{ position: 'relative', marginBottom: 14 }}>
              <div style={{
                position: 'absolute', left: -19, top: 0,
                width: 32, height: 32, borderRadius: 999,
                background: 'var(--surface-2)', border: '2px solid var(--surface)',
                display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 16,
              }}>{f.icon}</div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginLeft: 22 }}>
                <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--muted)', fontWeight: 600 }}>{f.ts}</span>
                <span style={{ fontSize: 13.5, color: 'var(--ink)', lineHeight: 1.5 }}>{f.text}</span>
              </div>
            </div>
          ))}
        </div>
      </Card>

      {/* Distribution card */}
      <Card style={{ background: 'var(--surface-2)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 18 }}>
          <div style={{ width: 56, height: 56, borderRadius: 14, background: 'var(--primary)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 26, flexShrink: 0 }}>📤</div>
          <div style={{ flex: 1 }}>
            <h4 style={{ fontFamily: 'var(--font-display)', fontSize: 16, fontWeight: 600, color: 'var(--ink)', margin: 0 }}>Distribuie raportul</h4>
            <p style={{ fontSize: 13, color: 'var(--ink-2)', margin: '4px 0 0', lineHeight: 1.5 }}>
              Vânzătorul atașează raportul la anunțul OLX / Imobiliare.ro · agentul îl primește semnat digital · cumpărătorul îl verifică pe blocapp.ro/scor/[ID]
            </p>
          </div>
          <Button variant="primary" icon="download" onClick={() => setShowShareModal(true)}>Generează</Button>
        </div>
      </Card>

      <ShareReportModal open={showShareModal} onClose={() => setShowShareModal(false)} score={score} />
    </div>
  );
}

function ScoreFact({ icon, text, warn }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
      <span style={{
        width: 18, height: 18, borderRadius: 999,
        background: warn ? 'rgba(245, 158, 11, 0.35)' : 'rgba(16, 185, 129, 0.35)',
        color: '#fff',
        display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 10, fontWeight: 700,
      }}>{icon}</span>
      <span>{text}</span>
    </div>
  );
}

function ScoreDimension({ label, icon, data }) {
  return (
    <Card>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
        <div style={{ fontSize: 28, flexShrink: 0 }}>{icon}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 11.5, color: 'var(--muted)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.04em' }}>{label}</div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginTop: 4 }}>
            <span style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 700, color: data.color }}>{data.score.toFixed(1)}</span>
            <span style={{ fontSize: 12, color: 'var(--muted)' }}>/ {data.max}</span>
            <span style={{ fontSize: 11, fontWeight: 600, color: data.color, marginLeft: 4 }}>· {data.label}</span>
          </div>
          {/* Stars */}
          <div style={{ marginTop: 6, display: 'flex', gap: 2 }}>
            {[1,2,3,4,5].map(i => (
              <span key={i} style={{ fontSize: 13, color: i <= Math.round(data.score) ? data.color : 'var(--neutral-bg)' }}>★</span>
            ))}
          </div>
          <div style={{ fontSize: 12, color: 'var(--ink-2)', marginTop: 8, lineHeight: 1.4 }}>{data.detail}</div>
        </div>
      </div>
    </Card>
  );
}

function ShareReportModal({ open, onClose, score }) {
  const toast = useToast();
  const reportUrl = `blocapp.ro/scor/bloc12-sb-${Math.random().toString(36).slice(2, 6).toUpperCase()}`;

  return (
    <Modal open={open} onClose={onClose} title="Raport public BlocApp Score"
      footer={<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
        <Button variant="secondary" onClick={onClose}>Închide</Button>
        <Button variant="primary" icon="download" onClick={() => { toast('Raport PDF descărcat'); onClose(); }}>Descarcă PDF</Button>
      </div>}
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        {/* Preview */}
        <div style={{
          padding: 24, borderRadius: 16,
          background: 'linear-gradient(135deg, #1F4738, #2d6a52)',
          color: '#fff',
          position: 'relative',
        }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 16 }}>
            <div>
              <div style={{ fontSize: 10, opacity: 0.7, textTransform: 'uppercase', letterSpacing: '0.1em', fontWeight: 700 }}>BLOCAPP SCORE · OFFICIAL</div>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 600, marginTop: 4 }}>{window.BUILDING.name}</div>
              <div style={{ fontSize: 11, opacity: 0.75, marginTop: 2 }}>{window.BUILDING.address}, {window.BUILDING.city}</div>
            </div>
            <div style={{ width: 72, height: 72, borderRadius: 14, background: 'rgba(255,255,255,0.15)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-display)', fontSize: 36, fontWeight: 700 }}>{score.grade}</div>
          </div>
          <div style={{ fontSize: 12, opacity: 0.85 }}>
            Generat 15 nov 2025 · valabil 30 zile · verificabil la <b>{reportUrl}</b>
          </div>
        </div>

        {/* Includes */}
        <div>
          <div style={{ fontSize: 12, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 600, marginBottom: 8 }}>Raportul conține</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6, fontSize: 13, color: 'var(--ink-2)' }}>
            <div>✓ Scor pe 6 dimensiuni cu detalii</div>
            <div>✓ Cuantum mediu lunar întreținere (ultimii 12 luni)</div>
            <div>✓ Lista verificărilor obligatorii cu termene</div>
            <div>✓ Lista lucrărilor mari ultimii 3 ani</div>
            <div>✓ Soldul actual al fondului de reparații</div>
            <div>✓ Eventuale procese în derulare (anonimizate)</div>
            <div>✗ Date personale ale locatarilor (GDPR)</div>
            <div>✗ Cuantumul exact pentru fiecare apartament</div>
          </div>
        </div>

        {/* Pricing */}
        <Card style={{ background: 'var(--surface-2)' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{ width: 36, height: 36, borderRadius: 10, background: 'var(--primary)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18 }}>💰</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)' }}>Cost generare: <b style={{ color: 'var(--primary)' }}>99 RON</b></div>
              <div style={{ fontSize: 11.5, color: 'var(--muted)', marginTop: 2 }}>Split 50/50 între vânzător și agent · acoperă serverul + verificarea independentă</div>
            </div>
          </div>
        </Card>
      </div>
    </Modal>
  );
}

Object.assign(window, { ScoreScreen });
