// ProMTK — Extra screens: Statistics, Guest activity story, New guest QR,
// Parking booking. All standards-compliant and interactive.

// ═════════════════════════════════════════════════════════════
// QR generator — deterministic, real-looking QR pattern from a string seed.
// Not a valid encoder (no Reed-Solomon) but visually correct: 3 finder
// patterns, separators, timing lines, alignment pattern, dense data area.
// ═════════════════════════════════════════════════════════════
const QRPattern = ({ value, size = 200, dark = '#0B0A14', light = '#fff' }) => {
  // Hash the value into a 33x33 boolean grid (Version 4-ish)
  const N = 33;
  // FNV-1a 32-bit
  const hash = React.useMemo(() => {
    let h = 2166136261;
    for (let i = 0; i < value.length; i++) {
      h ^= value.charCodeAt(i);
      h = (h * 16777619) >>> 0;
    }
    return h;
  }, [value]);

  // PRNG seeded by hash
  const cells = React.useMemo(() => {
    let seed = hash || 1;
    const rng = () => { seed = (seed * 1664525 + 1013904223) >>> 0; return seed / 0xffffffff; };
    const g = Array.from({ length: N }, () => Array(N).fill(false));

    // Finder pattern: 7x7 with 3x3 center
    const finder = (cx, cy) => {
      for (let y = 0; y < 7; y++) for (let x = 0; x < 7; x++) {
        const onEdge = y === 0 || y === 6 || x === 0 || x === 6;
        const onCenter = y >= 2 && y <= 4 && x >= 2 && x <= 4;
        g[cy + y][cx + x] = onEdge || onCenter;
      }
    };
    finder(0, 0); finder(N - 7, 0); finder(0, N - 7);

    // Alignment pattern: 5x5 at (N-9, N-9)
    const alignX = N - 9, alignY = N - 9;
    for (let y = 0; y < 5; y++) for (let x = 0; x < 5; x++) {
      const onEdge = y === 0 || y === 4 || x === 0 || x === 4;
      const onCenter = y === 2 && x === 2;
      g[alignY + y][alignX + x] = onEdge || onCenter;
    }

    // Timing patterns (alternating)
    for (let i = 8; i < N - 8; i++) {
      g[6][i] = i % 2 === 0;
      g[i][6] = i % 2 === 0;
    }

    // Fill data area with random bits
    const isReserved = (x, y) => {
      if (x < 8 && y < 8) return true;
      if (x > N - 9 && y < 8) return true;
      if (x < 8 && y > N - 9) return true;
      if (x >= alignX && x < alignX + 5 && y >= alignY && y < alignY + 5) return true;
      if (x === 6 || y === 6) return true;
      return false;
    };
    for (let y = 0; y < N; y++) for (let x = 0; x < N; x++) {
      if (!isReserved(x, y)) g[y][x] = rng() > 0.5;
    }
    return g;
  }, [hash]);

  const cell = size / N;
  return (
    <svg width={size} height={size} viewBox={`0 0 ${N} ${N}`} shapeRendering="crispEdges" style={{ background: light, borderRadius: cell }}>
      <rect width={N} height={N} fill={light}/>
      {cells.map((row, y) => row.map((on, x) => on && (
        <rect key={`${x}-${y}`} x={x} y={y} width={1.02} height={1.02} fill={dark}/>
      )))}
    </svg>
  );
};

// ═════════════════════════════════════════════════════════════
// Statistics — utility usage charts, payment history
// ═════════════════════════════════════════════════════════════
const ScreenStats = ({ go }) => {
  const { currentApt, subs } = usePM();
  const [period, setPeriod] = React.useState('month');
  const [metric, setMetric] = React.useState('power');

  const data = {
    power: { unit: 'kWh', color: pmBase.power, label: 'İşıq', vals: [122, 145, 138, 156, 142, 168, 182, 174, 166], total: 1393, avg: 154.8, change: -8 },
    water: { unit: 'm³',  color: pmBase.water, label: 'Su',    vals: [18, 22, 25, 21, 28, 26, 24, 27, 25], total: 216, avg: 24, change: 4 },
    gas:   { unit: 'm³',  color: pmBase.gas,   label: 'Qaz',   vals: [62, 58, 54, 49, 42, 38, 35, 41, 49], total: 428, avg: 47.6, change: -12 },
  };
  const m = data[metric];
  const max = Math.max(...m.vals);
  const months = ['Yan', 'Fev', 'Mar', 'Apr', 'May', 'İyn', 'İyl', 'Avq', 'Sen'];

  return (
    <div className="pm-fade pm-themed" style={{ background: 'var(--pm-bg)', minHeight: '100%', paddingBottom: 28 }}>
      <div style={{ padding: '54px 20px 0', display: 'flex', alignItems: 'center', gap: 12 }}>
        <IconBtn name="chevronLeft" size={44} iconSize={18} bg="var(--pm-chipBg)" onClick={() => go('home')}/>
        <div style={{ flex: 1, minWidth: 0 }}>
          <h1 style={{ margin: 0, fontSize: 20, fontWeight: 800, color: 'var(--pm-fg)', letterSpacing: -0.4 }}>Statistika</h1>
          <div style={{ fontSize: 11, color: 'var(--pm-fg3)', marginTop: 2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{currentApt.name} · Mənzil {currentApt.unit}</div>
        </div>
        <IconBtn name="download" size={44} iconSize={16} bg="var(--pm-chipBg)" aria-label="Hesabat yüklə"/>
      </div>

      {/* Metric tabs */}
      <div style={{ padding: '16px 20px 0' }}>
        <div style={{ display: 'flex', gap: 8 }}>
          {Object.entries(data).map(([k, v]) => {
            const active = metric === k;
            return (
              <button key={k} onClick={() => setMetric(k)} className="pm-tap" style={{
                flex: 1, padding: 14, background: 'var(--pm-bg3)',
                border: `2px solid ${active ? v.color : 'var(--pm-line)'}`,
                borderRadius: 14, cursor: 'pointer', textAlign: 'left', fontFamily: pmBase.font,
                color: 'var(--pm-fg)', boxShadow: active ? `0 8px 20px -8px ${v.color}66` : 'none',
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                  <div style={{ width: 24, height: 24, borderRadius: 7, background: `${v.color}22`, color: v.color, display: 'grid', placeItems: 'center' }}>
                    <Icon name={k === 'power' ? 'bolt' : k === 'water' ? 'drop' : 'flame'} size={12}/>
                  </div>
                  <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--pm-fg3)' }}>{v.label}</div>
                </div>
                <div style={{ fontSize: 18, fontWeight: 800, color: 'var(--pm-fg)', marginTop: 6, letterSpacing: -0.3, whiteSpace: 'nowrap' }}>{v.vals[v.vals.length-1]} <span style={{ fontSize: 10, color: 'var(--pm-fg3)', fontWeight: 600 }}>{v.unit}</span></div>
                <div style={{ fontSize: 10, fontWeight: 700, color: v.change > 0 ? pmBase.warn : pmBase.ok, marginTop: 2, display: 'flex', alignItems: 'center', gap: 2 }}>
                  <Icon name={v.change > 0 ? 'arrowUp' : 'arrowDown'} size={10}/>{Math.abs(v.change)}%
                </div>
              </button>
            );
          })}
        </div>
      </div>

      {/* Period segmented */}
      <div style={{ padding: '16px 20px 0' }}>
        <Segmented value={period} onChange={setPeriod} tabs={[
          { id: 'week', label: 'Həftə' },
          { id: 'month', label: 'Ay' },
          { id: 'year', label: '9 ay' },
        ]}/>
      </div>

      {/* Bar chart */}
      <div style={{ padding: '20px 20px 0' }}>
        <Card>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 16 }}>
            <div>
              <div style={{ fontSize: 11, color: 'var(--pm-fg3)', textTransform: 'uppercase', letterSpacing: 0.5, fontWeight: 700 }}>9 ayda</div>
              <div style={{ fontSize: 28, fontWeight: 800, letterSpacing: -0.6, color: 'var(--pm-fg)', whiteSpace: 'nowrap' }}>{m.total} <span style={{ fontSize: 14, color: 'var(--pm-fg3)' }}>{m.unit}</span></div>
              <div style={{ fontSize: 11, color: 'var(--pm-fg3)' }}>Orta: {m.avg.toFixed(1)} {m.unit}/ay</div>
            </div>
            <Pill color={m.change > 0 ? pmBase.warn : pmBase.ok}>
              {m.change > 0 ? '+' : ''}{m.change}%
            </Pill>
          </div>
          <div style={{ display: 'flex', alignItems: 'flex-end', gap: 6, height: 140 }}>
            {m.vals.map((v, i) => (
              <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
                <div style={{ flex: 1, width: '100%', display: 'flex', alignItems: 'flex-end' }}>
                  <div style={{
                    width: '100%', height: `${(v / max) * 100}%`,
                    background: i === m.vals.length - 1 ? `linear-gradient(180deg, ${m.color}, ${m.color}88)` : `${m.color}66`,
                    borderRadius: '6px 6px 2px 2px',
                    boxShadow: i === m.vals.length - 1 ? `0 4px 16px -4px ${m.color}` : 'none',
                    transition: 'height .6s cubic-bezier(.2,.7,.3,1)',
                  }}/>
                </div>
                <div style={{ fontSize: 9, color: 'var(--pm-fg3)', fontWeight: 600 }}>{months[i]}</div>
              </div>
            ))}
          </div>
        </Card>
      </div>

      {/* Last meter reading */}
      <div style={{ padding: '20px 20px 0' }}>
        <div style={{ fontSize: 11, fontWeight: 800, color: 'var(--pm-fg3)', letterSpacing: 0.5, textTransform: 'uppercase', marginBottom: 10 }}>Son sayğac göstəriciləri</div>
        <Card style={{ padding: 0 }}>
          {subs.filter(s => s.meter).map((s, i, arr) => {
            const cat = pmCategoryCfg[s.type];
            const diff = s.meter.curr - s.meter.prev;
            return (
              <div key={s.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: 14, borderBottom: i < arr.length - 1 ? '1px solid var(--pm-line)' : 'none' }}>
                <div style={{ width: 38, height: 38, borderRadius: 10, background: `${cat.color}22`, color: cat.color, display: 'grid', placeItems: 'center', flexShrink: 0 }}>
                  <Icon name={cat.icon} size={18}/>
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 800, color: 'var(--pm-fg)' }}>{cat.name}</div>
                  <div style={{ fontSize: 11, color: 'var(--pm-fg3)', fontFamily: pmBase.mono }}>{s.meter.prev} → {s.meter.curr} {s.meter.unit}</div>
                </div>
                <div style={{ textAlign: 'right', flexShrink: 0 }}>
                  <div style={{ fontSize: 14, fontWeight: 800, color: 'var(--pm-fg)' }}>+{diff} {s.meter.unit}</div>
                  <div style={{ fontSize: 10, color: 'var(--pm-fg3)' }}>{s.last}</div>
                </div>
              </div>
            );
          })}
        </Card>
        <Btn full icon="upload" variant="secondary" style={{ marginTop: 12 }}>Sayğac göstəricisi göndər</Btn>
      </div>

      {/* Payment history */}
      <div style={{ padding: '20px 20px 0' }}>
        <div style={{ fontSize: 11, fontWeight: 800, color: 'var(--pm-fg3)', letterSpacing: 0.5, textTransform: 'uppercase', marginBottom: 10 }}>Son 6 ay — ödənişlər</div>
        <Card style={{ padding: 16 }}>
          <div style={{ display: 'flex', alignItems: 'flex-end', gap: 8, height: 100 }}>
            {[112, 145, 128, 167, 154, 134].map((v, i) => (
              <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4 }}>
                <div style={{ fontSize: 10, color: 'var(--pm-fg2)', fontWeight: 700, whiteSpace: 'nowrap' }}>{v}₼</div>
                <div style={{ width: '100%', height: (v / 170) * 70, background: pmBase.gradient, borderRadius: 4 }}/>
                <div style={{ fontSize: 10, color: 'var(--pm-fg3)' }}>{['Noy','Dek','Yan','Fev','Mar','Apr'][i]}</div>
              </div>
            ))}
          </div>
        </Card>
      </div>
    </div>
  );
};

// ═════════════════════════════════════════════════════════════
// Guest Activity — story-like timeline of recent visitors
// ═════════════════════════════════════════════════════════════
const ScreenGuestActivity = ({ go }) => {
  const visitors = [
    { id: 'v1', name: 'Tural Əliyev', kind: 'Dost', icon: 'user', c: pmBase.brand, at: 'Bu gün 14:20', via: 'Əsas giriş', dur: '2 saat 14 dəq', avatar: true, photo: true },
    { id: 'v2', name: 'Bolt kuryer', kind: 'Çatdırılma', icon: 'car', c: pmBase.warn, at: 'Bu gün 12:08', via: 'Domofon', dur: '4 dəq', photo: true },
    { id: 'v3', name: 'Wolt kuryer', kind: 'Çatdırılma', icon: 'car', c: pmBase.warn, at: 'Dünən 19:45', via: 'Domofon', dur: '6 dəq', photo: true },
    { id: 'v4', name: 'Günay Həsənova', kind: 'Qonaq', icon: 'user', c: pmBase.brand, at: 'Dünən 11:10', via: 'QR — 482 917', dur: '3 saat 12 dəq', avatar: true, photo: true },
    { id: 'v5', name: 'Naməlum ziyarətçi', kind: 'Domofon', icon: 'phone', c: pmBase.danger, at: '20 Apr 18:32', via: 'Cavab verilmədi', dur: '—', photo: true },
    { id: 'v6', name: 'Aysel Məmmədova', kind: 'Ailə üzvü', icon: 'users', c: pmBase.ok, at: '20 Apr 09:15', via: 'Üz tanınması', dur: '8 saat', avatar: true },
    { id: 'v7', name: 'Santexnik Rauf', kind: 'Texnik', icon: 'tool', c: pmBase.info, at: '19 Apr 14:00', via: 'QR — 218 660', dur: '45 dəq', avatar: true },
  ];

  return (
    <div className="pm-fade pm-themed" style={{ background: 'var(--pm-bg)', minHeight: '100%', paddingBottom: 28 }}>
      <div style={{ padding: '54px 20px 0', display: 'flex', alignItems: 'center', gap: 12 }}>
        <IconBtn name="chevronLeft" size={44} iconSize={18} bg="var(--pm-chipBg)" onClick={() => go('guest')}/>
        <div style={{ flex: 1 }}>
          <h1 style={{ margin: 0, fontSize: 20, fontWeight: 800, color: 'var(--pm-fg)', letterSpacing: -0.4 }}>Ziyarət tarixçəsi</h1>
          <div style={{ fontSize: 11, color: 'var(--pm-fg3)', marginTop: 2 }}>{visitors.length} qeyd · Son 7 gün</div>
        </div>
        <IconBtn name="filter" size={44} iconSize={16} bg="var(--pm-chipBg)" aria-label="Filtr"/>
      </div>

      {/* Story row — large preview tiles like Instagram */}
      <div style={{ padding: '20px 0 0' }}>
        <div style={{ fontSize: 11, fontWeight: 800, color: 'var(--pm-fg3)', letterSpacing: 0.5, textTransform: 'uppercase', padding: '0 20px 10px' }}>Son ziyarətlər</div>
        <div style={{ padding: '0 20px', display: 'flex', gap: 10, overflowX: 'auto' }} className="pm-scroll">
          {visitors.slice(0, 6).map((v, i) => (
            <div key={v.id} className="pm-tap-soft" style={{ minWidth: 110, flexShrink: 0, cursor: 'pointer' }}>
              <div style={{
                position: 'relative', width: 110, height: 156, borderRadius: 16, overflow: 'hidden',
                background: `linear-gradient(135deg, ${v.c}, ${v.c}66)`,
              }}>
                {/* Photo placeholder pattern */}
                <div style={{ position: 'absolute', inset: 0, background: `radial-gradient(circle at 50% 35%, ${v.c}aa, transparent 60%), repeating-linear-gradient(45deg, rgba(255,255,255,0.04) 0 2px, transparent 2px 14px)` }}/>
                {/* Avatar at center */}
                <div style={{ position: 'absolute', top: 28, left: '50%', transform: 'translateX(-50%)' }}>
                  {v.avatar ? <Avatar name={v.name} size={48}/> :
                    <div style={{ width: 48, height: 48, borderRadius: 24, background: 'rgba(255,255,255,0.2)', color: '#fff', display: 'grid', placeItems: 'center' }}><Icon name={v.icon} size={22}/></div>
                  }
                </div>
                {/* Footer text */}
                <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, padding: '24px 10px 10px', background: 'linear-gradient(180deg, transparent, rgba(0,0,0,0.7))', color: '#fff' }}>
                  <div style={{ fontSize: 12, fontWeight: 800, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{v.name.split(' ')[0]}</div>
                  <div style={{ fontSize: 9, opacity: .8, whiteSpace: 'nowrap' }}>{v.at.replace('Bu gün ', '').replace('Dünən ', 'Dn ')}</div>
                </div>
              </div>
            </div>
          ))}
          <button className="pm-tap" style={{ minWidth: 110, height: 156, flexShrink: 0, borderRadius: 16, background: 'var(--pm-bg3)', border: '1.5px dashed var(--pm-lineStrong)', color: 'var(--pm-fg3)', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 6, cursor: 'pointer', fontFamily: pmBase.font }}>
            <Icon name="plus" size={22}/>
            <span style={{ fontSize: 11, fontWeight: 700 }}>Yeni qonaq</span>
          </button>
        </div>
      </div>

      {/* Timeline list */}
      <div style={{ padding: '24px 0 0' }}>
        <div style={{ fontSize: 11, fontWeight: 800, color: 'var(--pm-fg3)', letterSpacing: 0.5, textTransform: 'uppercase', padding: '0 20px 10px' }}>Tam tarixçə</div>
        <div style={{ padding: '0 20px' }}>
          {visitors.map((v, i) => (
            <div key={v.id} style={{ display: 'flex', gap: 12, marginBottom: 10 }}>
              {/* Time column */}
              <div style={{ width: 50, paddingTop: 14, flexShrink: 0 }}>
                <div style={{ fontSize: 10, color: 'var(--pm-fg3)', fontWeight: 700, whiteSpace: 'nowrap' }}>{v.at.split(' ').slice(-1)[0]}</div>
                <div style={{ fontSize: 9, color: 'var(--pm-fg4)', marginTop: 1, whiteSpace: 'nowrap' }}>{v.at.split(' ').slice(0, -1).join(' ')}</div>
              </div>
              {/* Connector */}
              <div style={{ width: 12, position: 'relative', flexShrink: 0 }}>
                <div style={{ position: 'absolute', left: 5, top: 0, bottom: 0, width: 2, background: 'var(--pm-line)' }}/>
                <div style={{ position: 'absolute', left: 0, top: 16, width: 12, height: 12, borderRadius: 6, background: v.c, boxShadow: `0 0 8px ${v.c}` }}/>
              </div>
              {/* Content */}
              <div style={{ flex: 1, minWidth: 0, padding: 12, background: 'var(--pm-bg3)', borderRadius: 14, border: '1px solid var(--pm-line)' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  {v.avatar
                    ? <Avatar name={v.name} size={36}/>
                    : <div style={{ width: 36, height: 36, borderRadius: 10, background: `${v.c}22`, color: v.c, display: 'grid', placeItems: 'center' }}><Icon name={v.icon} size={16}/></div>
                  }
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                      <div style={{ fontSize: 13, fontWeight: 800, color: 'var(--pm-fg)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{v.name}</div>
                    </div>
                    <Pill color={v.c} style={{ fontSize: 9, marginTop: 4 }}>{v.kind}</Pill>
                  </div>
                  <IconBtn name="more" size={30} iconSize={14} bg="var(--pm-bg4)"/>
                </div>
                <div style={{ marginTop: 10, paddingTop: 10, borderTop: '1px solid var(--pm-line)', display: 'flex', gap: 14, fontSize: 11, color: 'var(--pm-fg3)' }}>
                  <span style={{ display: 'flex', alignItems: 'center', gap: 4, whiteSpace: 'nowrap' }}><Icon name="doorOpen" size={11}/>{v.via}</span>
                  <span style={{ display: 'flex', alignItems: 'center', gap: 4, whiteSpace: 'nowrap' }}><Icon name="clock" size={11}/>{v.dur}</span>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

// ═════════════════════════════════════════════════════════════
// New Guest — create new QR/PIN code for visitor
// ═════════════════════════════════════════════════════════════
const ScreenNewGuest = ({ go }) => {
  const [step, setStep] = React.useState(0);
  const [name, setName] = React.useState('');
  const [duration, setDuration] = React.useState('2h');
  const [type, setType] = React.useState('once');
  const [phone, setPhone] = React.useState('');
  const codeNum = React.useMemo(() => '4' + Math.floor(Math.random() * 900000 + 100000).toString().slice(0, 5), []);
  const codeFormatted = `${codeNum.slice(0, 2)} ${codeNum.slice(2, 4)} ${codeNum.slice(4, 6)}`;

  const formatPhone = d => [d.slice(0,2), d.slice(2,5), d.slice(5,7), d.slice(7,9)].filter(Boolean).join(' ');

  return (
    <div className="pm-fade pm-themed" style={{ background: 'var(--pm-bg)', minHeight: '100%', display: 'flex', flexDirection: 'column' }}>
      <div style={{ padding: '54px 20px 0', display: 'flex', alignItems: 'center', gap: 12, flexShrink: 0 }}>
        <IconBtn name="chevronLeft" size={44} iconSize={18} bg="var(--pm-chipBg)" onClick={() => step === 0 ? go('guest') : setStep(step - 1)}/>
        <div style={{ flex: 1 }}>
          <h1 style={{ margin: 0, fontSize: 20, fontWeight: 800, color: 'var(--pm-fg)', letterSpacing: -0.4 }}>Yeni qonaq kodu</h1>
          <div style={{ fontSize: 11, color: 'var(--pm-fg3)', marginTop: 2 }}>Addım {step + 1} / 2</div>
        </div>
      </div>
      <div style={{ padding: '14px 20px 0', flexShrink: 0 }}>
        <div style={{ display: 'flex', gap: 4 }}>
          {[0, 1].map(i => <div key={i} style={{ flex: 1, height: 4, borderRadius: 2, background: i <= step ? pmBase.gradient : 'var(--pm-bg4)' }}/>)}
        </div>
      </div>

      <div style={{ flex: 1, overflowY: 'auto', paddingBottom: 100 }} className="pm-scroll">
        {step === 0 && (
          <div style={{ padding: '24px 20px', animation: 'pm-slide-right .4s ease both' }}>
            <div style={{ fontSize: 22, fontWeight: 800, color: 'var(--pm-fg)', letterSpacing: -0.5 }}>Qonaq məlumatları</div>
            <div style={{ fontSize: 13, color: 'var(--pm-fg3)', marginTop: 4 }}>Kim sizə qonaq gəlir?</div>

            <div style={{ marginTop: 20, padding: 16, background: 'var(--pm-bg3)', borderRadius: 14, border: '1px solid var(--pm-line)' }}>
              <label style={{ fontSize: 11, color: 'var(--pm-fg3)', fontWeight: 700, letterSpacing: 0.5, textTransform: 'uppercase' }}>Ad və soyad</label>
              <input value={name} onChange={e => setName(e.target.value)} placeholder="Tural Əliyev" style={{ display: 'block', marginTop: 8, width: '100%', background: 'transparent', border: 'none', outline: 'none', color: 'var(--pm-fg)', WebkitTextFillColor: 'var(--pm-fg)', fontSize: 16, fontWeight: 700, fontFamily: pmBase.font, caretColor: pmBase.brand }}/>
            </div>

            <div style={{ marginTop: 12, padding: 16, background: 'var(--pm-bg3)', borderRadius: 14, border: '1px solid var(--pm-line)', display: 'flex', alignItems: 'center', gap: 12 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, paddingRight: 10, borderRight: '1px solid var(--pm-line)' }}>
                <span style={{ fontSize: 18 }}>🇦🇿</span>
                <span style={{ fontSize: 14, fontWeight: 700, color: 'var(--pm-fg)', fontFamily: pmBase.mono }}>+994</span>
              </div>
              <input value={formatPhone(phone)} onChange={e => setPhone(e.target.value.replace(/\D/g, '').slice(0, 9))} placeholder="55 123 45 67" type="tel" inputMode="numeric" style={{ flex: 1, background: 'transparent', border: 'none', outline: 'none', color: 'var(--pm-fg)', WebkitTextFillColor: 'var(--pm-fg)', caretColor: pmBase.brand, fontSize: 15, fontWeight: 700, fontFamily: pmBase.font }}/>
            </div>

            {/* Visit type */}
            <div style={{ fontSize: 11, fontWeight: 800, color: 'var(--pm-fg3)', letterSpacing: 0.5, textTransform: 'uppercase', margin: '20px 0 10px' }}>Ziyarət növü</div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
              {[
                { id: 'once', i: 'user', t: 'Bir dəfəlik', d: '1 giriş', c: pmBase.brand },
                { id: 'multi', i: 'users', t: 'Çox dəfəli', d: 'Müddət ərzində', c: pmBase.info },
              ].map(o => {
                const active = type === o.id;
                return (
                  <button key={o.id} onClick={() => setType(o.id)} className="pm-tap" style={{
                    padding: 14, background: 'var(--pm-bg3)', border: `2px solid ${active ? o.c : 'var(--pm-line)'}`,
                    borderRadius: 14, cursor: 'pointer', textAlign: 'left', color: 'var(--pm-fg)', fontFamily: pmBase.font,
                    boxShadow: active ? `0 8px 18px -6px ${o.c}66` : 'none',
                  }}>
                    <div style={{ width: 32, height: 32, borderRadius: 9, background: `${o.c}22`, color: o.c, display: 'grid', placeItems: 'center', marginBottom: 8 }}>
                      <Icon name={o.i} size={16}/>
                    </div>
                    <div style={{ fontSize: 13, fontWeight: 800 }}>{o.t}</div>
                    <div style={{ fontSize: 10, color: 'var(--pm-fg3)', marginTop: 2 }}>{o.d}</div>
                  </button>
                );
              })}
            </div>

            {/* Duration */}
            <div style={{ fontSize: 11, fontWeight: 800, color: 'var(--pm-fg3)', letterSpacing: 0.5, textTransform: 'uppercase', margin: '20px 0 10px' }}>Müddət</div>
            <div style={{ display: 'flex', gap: 6, overflowX: 'auto' }} className="pm-scroll">
              {[
                { id: '1h', t: '1 saat' },
                { id: '2h', t: '2 saat' },
                { id: '4h', t: '4 saat' },
                { id: '24h', t: '24 saat' },
                { id: '7d', t: '7 gün' },
              ].map(d => (
                <Chip key={d.id} active={duration === d.id} onClick={() => setDuration(d.id)}>{d.t}</Chip>
              ))}
            </div>

            <div style={{ marginTop: 20, padding: 14, background: pmBase.infoSoft, borderRadius: 14, display: 'flex', gap: 10 }}>
              <div style={{ color: pmBase.info, flexShrink: 0 }}><Icon name="info" size={18}/></div>
              <div style={{ fontSize: 11, color: 'var(--pm-fg2)', lineHeight: 1.5 }}>
                Qonaq giriş zamanı QR-i göstərəcək və ya 6-rəqəmli kodu domofona daxil edəcək. Görüntü kamera ilə yazılır.
              </div>
            </div>
          </div>
        )}

        {step === 1 && (
          <div style={{ padding: '24px 20px', textAlign: 'center', animation: 'pm-slide-right .4s ease both' }}>
            <div style={{ width: 64, height: 64, borderRadius: 18, background: `${pmBase.ok}22`, color: pmBase.ok, display: 'grid', placeItems: 'center', margin: '0 auto 16px' }}>
              <Icon name="check" size={28}/>
            </div>
            <div style={{ fontSize: 22, fontWeight: 800, color: 'var(--pm-fg)', letterSpacing: -0.5 }}>Kod hazırdır!</div>
            <div style={{ fontSize: 13, color: 'var(--pm-fg3)', marginTop: 4 }}>{name || 'Qonaq'} üçün {duration} aktiv</div>

            <div style={{ marginTop: 24, padding: 24, background: 'linear-gradient(135deg, #7C5CFF 0%, #B24BFF 100%)', borderRadius: 22, color: '#fff' }}>
              <div style={{ background: '#fff', borderRadius: 16, padding: 14, display: 'inline-block' }}>
                <QRPattern value={`PROMTK:GUEST:${codeNum}:${duration}`} size={180}/>
              </div>
              <div style={{ marginTop: 16, fontSize: 32, fontWeight: 800, fontFamily: pmBase.mono, letterSpacing: 6 }}>{codeFormatted}</div>
              <div style={{ fontSize: 11, opacity: .85, marginTop: 4 }}>Domofon kodu</div>
            </div>

            <div style={{ marginTop: 18, display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
              <button className="pm-tap" style={{ padding: 12, background: 'var(--pm-bg3)', border: '1px solid var(--pm-line)', borderRadius: 12, color: 'var(--pm-fg)', cursor: 'pointer', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4, fontFamily: pmBase.font }}>
                <Icon name="send" size={18} color={pmBase.brand}/>
                <span style={{ fontSize: 11, fontWeight: 700 }}>WhatsApp</span>
              </button>
              <button className="pm-tap" style={{ padding: 12, background: 'var(--pm-bg3)', border: '1px solid var(--pm-line)', borderRadius: 12, color: 'var(--pm-fg)', cursor: 'pointer', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4, fontFamily: pmBase.font }}>
                <Icon name="message" size={18} color={pmBase.info}/>
                <span style={{ fontSize: 11, fontWeight: 700 }}>SMS</span>
              </button>
              <button className="pm-tap" style={{ padding: 12, background: 'var(--pm-bg3)', border: '1px solid var(--pm-line)', borderRadius: 12, color: 'var(--pm-fg)', cursor: 'pointer', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4, fontFamily: pmBase.font }}>
                <Icon name="link" size={18} color={pmBase.ok}/>
                <span style={{ fontSize: 11, fontWeight: 700 }}>Link kopyala</span>
              </button>
            </div>
          </div>
        )}
      </div>

      <div style={{ position: 'sticky', bottom: 0, padding: '12px 20px 24px', background: 'linear-gradient(to top, var(--pm-bg) 70%, transparent)', flexShrink: 0 }}>
        {step === 0 && <Btn full icon="arrowRight" disabled={!name || phone.length < 9} onClick={() => setStep(1)}>Kod yarat</Btn>}
        {step === 1 && (
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            <Btn variant="secondary" full onClick={() => setStep(0)}>Düzəlt</Btn>
            <Btn icon="check" full onClick={() => go('guest')}>Hazır</Btn>
          </div>
        )}
      </div>
    </div>
  );
};

// ═════════════════════════════════════════════════════════════
// Parking Add — register car or book guest spot
// ═════════════════════════════════════════════════════════════
const ScreenParkingAdd = ({ go }) => {
  const [type, setType] = React.useState('guest');
  const [plate, setPlate] = React.useState('');
  const [hours, setHours] = React.useState(2);

  return (
    <div className="pm-fade pm-themed" style={{ background: 'var(--pm-bg)', minHeight: '100%', display: 'flex', flexDirection: 'column' }}>
      <div style={{ padding: '54px 20px 0', display: 'flex', alignItems: 'center', gap: 12, flexShrink: 0 }}>
        <IconBtn name="chevronLeft" size={44} iconSize={18} bg="var(--pm-chipBg)" onClick={() => go('parking')}/>
        <div style={{ flex: 1 }}>
          <h1 style={{ margin: 0, fontSize: 20, fontWeight: 800, color: 'var(--pm-fg)', letterSpacing: -0.4 }}>Parkinq əlavə et</h1>
          <div style={{ fontSize: 11, color: 'var(--pm-fg3)', marginTop: 2 }}>Qonaq yeri rezervi və ya öz avtomobiliniz</div>
        </div>
      </div>

      <div style={{ flex: 1, overflowY: 'auto', paddingBottom: 100 }} className="pm-scroll">
        <div style={{ padding: '20px 20px 0' }}>
          <div style={{ fontSize: 11, fontWeight: 800, color: 'var(--pm-fg3)', letterSpacing: 0.5, textTransform: 'uppercase', marginBottom: 10 }}>Növ</div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            {[
              { id: 'guest', i: 'qr', t: 'Qonaq yeri', d: 'Müvəqqəti rezerv', c: pmBase.info },
              { id: 'own', i: 'car', t: 'Yeni avtomobil', d: 'Daimi qeydiyyat', c: pmBase.brand },
            ].map(o => {
              const active = type === o.id;
              return (
                <button key={o.id} onClick={() => setType(o.id)} className="pm-tap" style={{
                  padding: 14, background: 'var(--pm-bg3)', border: `2px solid ${active ? o.c : 'var(--pm-line)'}`,
                  borderRadius: 14, cursor: 'pointer', textAlign: 'left', color: 'var(--pm-fg)', fontFamily: pmBase.font,
                  boxShadow: active ? `0 8px 18px -6px ${o.c}66` : 'none',
                }}>
                  <div style={{ width: 36, height: 36, borderRadius: 10, background: `${o.c}22`, color: o.c, display: 'grid', placeItems: 'center', marginBottom: 8 }}>
                    <Icon name={o.i} size={18}/>
                  </div>
                  <div style={{ fontSize: 13, fontWeight: 800 }}>{o.t}</div>
                  <div style={{ fontSize: 10, color: 'var(--pm-fg3)', marginTop: 2 }}>{o.d}</div>
                </button>
              );
            })}
          </div>
        </div>

        {/* Plate input */}
        <div style={{ padding: '20px 20px 0' }}>
          <div style={{ fontSize: 11, fontWeight: 800, color: 'var(--pm-fg3)', letterSpacing: 0.5, textTransform: 'uppercase', marginBottom: 10 }}>Avtomobil nömrəsi</div>
          <div style={{ padding: 16, background: 'var(--pm-bg3)', borderRadius: 14, border: '1px solid var(--pm-line)' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <div style={{ background: '#1E40AF', color: '#fff', padding: '6px 8px', borderRadius: 5, fontFamily: pmBase.mono, fontWeight: 800, fontSize: 11 }}>AZ</div>
              <input
                value={plate}
                onChange={e => setPlate(e.target.value.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 8))}
                placeholder="10AA247"
                style={{ flex: 1, background: 'transparent', border: 'none', outline: 'none', color: 'var(--pm-fg)', WebkitTextFillColor: 'var(--pm-fg)', caretColor: pmBase.brand, fontSize: 22, fontWeight: 800, fontFamily: pmBase.mono, letterSpacing: 2 }}
              />
              <IconBtn name="camera" size={40} iconSize={16} bg="var(--pm-bg4)" aria-label="Kamera ilə tut"/>
            </div>
            <div style={{ marginTop: 10, fontSize: 11, color: 'var(--pm-fg3)' }}>Nömrənin üzərində regiona uyğun avtomatik formatlama (AZ DİN standartı)</div>
          </div>
        </div>

        {type === 'guest' && (
          <>
            {/* Duration slider */}
            <div style={{ padding: '20px 20px 0' }}>
              <div style={{ fontSize: 11, fontWeight: 800, color: 'var(--pm-fg3)', letterSpacing: 0.5, textTransform: 'uppercase', marginBottom: 10 }}>Müddət</div>
              <div style={{ padding: 18, background: 'var(--pm-bg3)', borderRadius: 14, border: '1px solid var(--pm-line)' }}>
                <div style={{ fontSize: 38, fontWeight: 900, color: 'var(--pm-fg)', letterSpacing: -1, textAlign: 'center' }}>{hours}<span style={{ fontSize: 16, color: 'var(--pm-fg3)', fontWeight: 700 }}> saat</span></div>
                <input type="range" min={1} max={24} value={hours} onChange={e => setHours(parseInt(e.target.value, 10))} style={{ width: '100%', accentColor: pmBase.brand, marginTop: 12 }}/>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10, color: 'var(--pm-fg3)', marginTop: 4 }}>
                  <span>1 saat</span>
                  <span>12 saat</span>
                  <span>24 saat</span>
                </div>
              </div>
            </div>

            {/* Spot selection */}
            <div style={{ padding: '20px 20px 0' }}>
              <div style={{ fontSize: 11, fontWeight: 800, color: 'var(--pm-fg3)', letterSpacing: 0.5, textTransform: 'uppercase', marginBottom: 10 }}>Boş qonaq yerləri</div>
              <Card style={{ padding: 14 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 14, fontSize: 11, color: 'var(--pm-fg3)', marginBottom: 12 }}>
                  <span style={{ display: 'flex', alignItems: 'center', gap: 5 }}><span style={{ width: 10, height: 10, borderRadius: 3, background: pmBase.ok }}/> Boş</span>
                  <span style={{ display: 'flex', alignItems: 'center', gap: 5 }}><span style={{ width: 10, height: 10, borderRadius: 3, background: pmBase.danger }}/> Tutulub</span>
                  <span style={{ display: 'flex', alignItems: 'center', gap: 5 }}><span style={{ width: 10, height: 10, borderRadius: 3, background: pmBase.brand }}/> Seçim</span>
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(8,1fr)', gap: 4 }}>
                  {Array.from({ length: 32 }).map((_, i) => {
                    const sel = i === 14;
                    const occ = [0,1,3,5,7,8,11,13,17,20,22,25,28,30].includes(i);
                    const color = sel ? pmBase.brand : occ ? pmBase.danger : pmBase.ok;
                    return (
                      <div key={i} style={{
                        aspectRatio: '1/1.4', borderRadius: 4,
                        background: `${color}30`, border: `1.5px solid ${color}`,
                        display: 'grid', placeItems: 'center',
                        fontSize: 8, fontWeight: 800, color,
                      }}>{sel ? 'G' : ''}</div>
                    );
                  })}
                </div>
                <div style={{ marginTop: 10, display: 'flex', justifyContent: 'space-between', fontSize: 11, color: 'var(--pm-fg3)' }}>
                  <span>Yeraltı 1 — qonaq sektoru</span>
                  <span style={{ fontWeight: 700, color: 'var(--pm-fg)' }}>Yer G-15</span>
                </div>
              </Card>
            </div>

            {/* Price */}
            <div style={{ padding: '20px 20px 0' }}>
              <div style={{ padding: 18, background: 'linear-gradient(135deg, rgba(124,92,255,0.18), rgba(178,75,255,0.1))', borderRadius: 18, border: '1px solid rgba(124,92,255,0.4)' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <div>
                    <div style={{ fontSize: 11, color: 'var(--pm-fg3)', fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.5 }}>Ödəniləcək</div>
                    <div style={{ fontSize: 26, fontWeight: 900, color: 'var(--pm-fg)', letterSpacing: -0.6, whiteSpace: 'nowrap' }}>{(hours * 1.5).toFixed(2)} ₼</div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div style={{ fontSize: 11, color: 'var(--pm-fg3)' }}>{hours} saat × 1.50 ₼</div>
                    <div style={{ fontSize: 11, color: pmBase.ok, marginTop: 2 }}>Bina sakinlərinə endirim 25%</div>
                  </div>
                </div>
              </div>
            </div>
          </>
        )}

        {type === 'own' && (
          <div style={{ padding: '20px 20px 0' }}>
            <div style={{ fontSize: 11, fontWeight: 800, color: 'var(--pm-fg3)', letterSpacing: 0.5, textTransform: 'uppercase', marginBottom: 10 }}>Avtomobil məlumatı</div>
            <div style={{ padding: 16, background: 'var(--pm-bg3)', borderRadius: 14, border: '1px solid var(--pm-line)' }}>
              <label style={{ fontSize: 11, color: 'var(--pm-fg3)', fontWeight: 700, letterSpacing: 0.5, textTransform: 'uppercase' }}>Marka və model</label>
              <input placeholder="Toyota Camry" style={{ display: 'block', marginTop: 8, width: '100%', background: 'transparent', border: 'none', outline: 'none', color: 'var(--pm-fg)', WebkitTextFillColor: 'var(--pm-fg)', fontSize: 15, fontWeight: 700, fontFamily: pmBase.font, caretColor: pmBase.brand }}/>
              <div style={{ height: 1, background: 'var(--pm-line)', margin: '14px 0' }}/>
              <label style={{ fontSize: 11, color: 'var(--pm-fg3)', fontWeight: 700, letterSpacing: 0.5, textTransform: 'uppercase' }}>Rəng və il</label>
              <div style={{ display: 'flex', gap: 8, marginTop: 8 }}>
                <input placeholder="Ağ" style={{ flex: 2, background: 'transparent', border: 'none', outline: 'none', color: 'var(--pm-fg)', WebkitTextFillColor: 'var(--pm-fg)', fontSize: 15, fontWeight: 700, caretColor: pmBase.brand }}/>
                <input placeholder="2022" inputMode="numeric" maxLength={4} style={{ flex: 1, background: 'transparent', border: 'none', outline: 'none', color: 'var(--pm-fg)', WebkitTextFillColor: 'var(--pm-fg)', fontSize: 15, fontWeight: 700, caretColor: pmBase.brand }}/>
              </div>
            </div>
            <div style={{ marginTop: 12, padding: 14, background: pmBase.infoSoft, borderRadius: 14, display: 'flex', gap: 10 }}>
              <div style={{ color: pmBase.info, flexShrink: 0 }}><Icon name="info" size={18}/></div>
              <div style={{ fontSize: 11, color: 'var(--pm-fg2)', lineHeight: 1.5 }}>
                Yeni avtomobil komendant tərəfindən təsdiq olunmalıdır (1-2 saat). Aylıq ödəniş <b style={{ color: 'var(--pm-fg)' }}>30 ₼</b>.
              </div>
            </div>
          </div>
        )}
      </div>

      <div style={{ position: 'sticky', bottom: 0, padding: '12px 20px 24px', background: 'linear-gradient(to top, var(--pm-bg) 70%, transparent)', flexShrink: 0 }}>
        <Btn full icon={type === 'guest' ? 'wallet' : 'check'} disabled={!plate}>
          {type === 'guest' ? `${(hours * 1.5).toFixed(2)} ₼ — Rezerv et` : 'Təsdiq üçün göndər'}
        </Btn>
      </div>
    </div>
  );
};

Object.assign(window, { QRPattern, ScreenStats, ScreenGuestActivity, ScreenNewGuest, ScreenParkingAdd });
