// DocumentsScreen — Upload personal documents: national ID front/back + IBAN.

const { useState: useStateD, useRef: useRefD, useMemo: useMemoD } = React;

const faNumD = (n) => String(n).replace(/\d/g, d => '۰۱۲۳۴۵۶۷۸۹'[d]);
const toFaDigits = (s) => String(s).replace(/[0-9]/g, d => '۰۱۲۳۴۵۶۷۸۹'[d]);
const toEnDigits = (s) => String(s).replace(/[۰-۹]/g, d => '۰۱۲۳۴۵۶۷۸۹'.indexOf(d));

// Group 24 digits into 4-4-4-4-4-4 for IBAN display
const formatIban = (raw) => {
  const digits = raw.replace(/\D/g, '').slice(0, 24);
  return digits.match(/.{1,4}/g)?.join(' ') ?? '';
};

function PhotoSlot({ label, hint, file, onPick, onClear }) {
  const ref = useRefD();
  const url = useMemoD(() => file ? URL.createObjectURL(file) : null, [file]);
  return (
    <div>
      <div style={{
        fontSize: 11.5, color: 'var(--muted)', letterSpacing: '0.02em',
        marginBottom: 6, fontWeight: 500, padding: '0 2px',
        display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
      }}>
        <span>{label}</span>
        {file && (
          <button onClick={onClear} style={{
            all: 'unset', cursor: 'pointer', fontSize: 11,
            color: 'var(--danger)', fontWeight: 600,
          }}>حذف</button>
        )}
      </div>
      <input
        ref={ref}
        type="file"
        accept="image/*"
        capture="environment"
        style={{ display: 'none' }}
        onChange={(e) => onPick(e.target.files?.[0])}
      />
      {!url ? (
        <button onClick={() => ref.current?.click()} style={{
          all: 'unset', cursor: 'pointer', width: '100%', boxSizing: 'border-box',
          aspectRatio: '1.586 / 1', // standard ID-1 card ratio
          border: '1.5px dashed var(--border)',
          borderRadius: 14,
          background: 'var(--icon-bg)',
          display: 'flex', flexDirection: 'column',
          alignItems: 'center', justifyContent: 'center', gap: 8,
          textAlign: 'center',
        }}>
          <div style={{
            width: 40, height: 40, borderRadius: 12,
            background: 'var(--surface)', border: '1px solid var(--border)',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: 'var(--accent)',
          }}>
            <window.IconUpload size={20} color="currentColor" />
          </div>
          <div style={{ fontSize: 12.5, fontWeight: 600, color: 'var(--ink)' }}>
            افزودن عکس
          </div>
          <div style={{ fontSize: 10.5, color: 'var(--muted)', padding: '0 12px' }}>
            {hint}
          </div>
        </button>
      ) : (
        <div style={{
          position: 'relative', borderRadius: 14, overflow: 'hidden',
          aspectRatio: '1.586 / 1',
          border: '1px solid var(--border)',
          background: 'var(--icon-bg)',
        }}>
          <img src={url} alt={label}
               style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
          <button
            onClick={() => ref.current?.click()}
            style={{
              all: 'unset', cursor: 'pointer',
              position: 'absolute', top: 8, right: 8,
              fontSize: 11, fontWeight: 600, color: '#fff',
              background: 'rgba(0,0,0,0.55)',
              padding: '5px 10px', borderRadius: 99,
              backdropFilter: 'blur(8px)',
            }}>تغییر</button>
          <div style={{
            position: 'absolute', bottom: 8, left: 8,
            display: 'inline-flex', alignItems: 'center', gap: 5,
            fontSize: 10.5, fontWeight: 600, color: '#fff',
            background: 'rgba(8,80,60,0.7)',
            padding: '4px 9px', borderRadius: 99,
            backdropFilter: 'blur(8px)',
          }}>
            <window.IconCheck size={12} color="#fff" />
            <span>ثبت شد</span>
          </div>
        </div>
      )}
    </div>
  );
}

function DocumentsScreen({ onBack, onSubmit }) {
  const [idFront, setIdFront] = useStateD(null);
  const [idBack, setIdBack]   = useStateD(null);
  const [iban, setIban]       = useStateD('');
  const [submitted, setSubmitted] = useStateD(false);

  // raw digits for validation
  const ibanDigits = iban.replace(/\D/g, '');
  const ibanComplete = ibanDigits.length === 24;
  const ibanInvalid = iban.length > 0 && ibanDigits.length > 0 && !ibanComplete;

  const ready = !!idFront && !!idBack && ibanComplete;

  const completion = [
    { label: 'روی کارت ملی', done: !!idFront },
    { label: 'پشت کارت ملی', done: !!idBack },
    { label: 'شماره شبا',     done: ibanComplete },
  ];
  const doneCount = completion.filter(c => c.done).length;

  const handleSubmit = () => {
    if (!ready || submitted) return;
    setSubmitted(true);
    setTimeout(() => {
      onSubmit?.({ idFront, idBack, iban: ibanDigits });
    }, 700);
  };

  // handle iban input: store as formatted string with spaces, fa digits in display only
  const onIbanChange = (e) => {
    const cleaned = toEnDigits(e.target.value).replace(/\D/g, '').slice(0, 24);
    setIban(cleaned);
  };

  const ibanDisplay = formatIban(ibanDigits);

  return (
    <div style={{
      direction: 'rtl', background: 'var(--bg)',
      height: '100%',
      fontFamily: 'Vazirmatn, system-ui, sans-serif', color: 'var(--ink)',
      display: 'flex', flexDirection: 'column', overflow: 'hidden',
    }}>
      {/* header */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '14px 18px 8px', flexShrink: 0,
      }}>
        <button onClick={onBack} style={{
          all: 'unset', cursor: 'pointer',
          width: 38, height: 38, borderRadius: 99,
          background: 'var(--surface)', border: '1px solid var(--border)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: 'var(--ink)',
        }}>
          <window.IconChevron size={16} dir="right" />
        </button>
        <div style={{ textAlign: 'center' }}>
          <div style={{ fontSize: 15, fontWeight: 700 }}>آپلود مدارک</div>
          <div style={{ fontSize: 11, color: 'var(--muted)' }}>کارت ملی و اطلاعات بانکی</div>
        </div>
        <div style={{ width: 38 }} />
      </div>

      <div style={{ flex: 1, overflowY: 'auto', padding: '8px 18px 14px' }}>
        {/* progress strip */}
        <div style={{
          background: 'var(--surface)', border: '1px solid var(--border)',
          borderRadius: 14, padding: '12px 14px', marginBottom: 16,
        }}>
          <div style={{
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            marginBottom: 10,
          }}>
            <div style={{ fontSize: 12, color: 'var(--muted)' }}>پیشرفت</div>
            <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--ink)' }}>
              {faNumD(doneCount)} از {faNumD(3)}
            </div>
          </div>
          <div style={{
            height: 6, borderRadius: 99, background: 'var(--icon-bg)',
            overflow: 'hidden',
          }}>
            <div style={{
              height: '100%', width: `${(doneCount / 3) * 100}%`,
              background: 'var(--accent)',
              transition: 'width 280ms cubic-bezier(.2,.8,.2,1)',
            }} />
          </div>
        </div>

        {/* ID card section */}
        <div style={{
          fontSize: 11, color: 'var(--muted)', letterSpacing: '0.04em',
          marginBottom: 8, fontWeight: 500, padding: '0 2px',
        }}>کارت ملی</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14, marginBottom: 18 }}>
          <PhotoSlot
            label="روی کارت ملی"
            hint="عکس واضح، بدون انعکاس نور"
            file={idFront}
            onPick={setIdFront}
            onClear={() => setIdFront(null)}
          />
          <PhotoSlot
            label="پشت کارت ملی"
            hint="کد سریال در پایین کارت خوانا باشد"
            file={idBack}
            onPick={setIdBack}
            onClear={() => setIdBack(null)}
          />
        </div>

        {/* IBAN section */}
        <div style={{
          fontSize: 11, color: 'var(--muted)', letterSpacing: '0.04em',
          marginBottom: 8, fontWeight: 500, padding: '0 2px',
        }}>اطلاعات بانکی</div>

        <div style={{
          background: 'var(--surface)', border: `1px solid ${ibanInvalid ? 'var(--danger)' : 'var(--border)'}`,
          borderRadius: 14, padding: '12px 14px',
          transition: 'border-color 160ms ease',
        }}>
          <div style={{
            fontSize: 11, color: 'var(--muted)', marginBottom: 8,
            display: 'flex', alignItems: 'center', gap: 6,
          }}>
            <window.IconBank size={14} color="currentColor" />
            <span>شماره شبا (۲۴ رقم بدون IR)</span>
          </div>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 10,
            direction: 'ltr',
          }}>
            <span style={{
              fontSize: 14, fontWeight: 700, color: 'var(--muted)',
              fontFamily: 'JetBrains Mono, ui-monospace, monospace',
              letterSpacing: '0.05em',
            }}>IR</span>
            <input
              type="text"
              inputMode="numeric"
              value={toFaDigits(ibanDisplay)}
              onChange={onIbanChange}
              placeholder="۰۶۲۹ ۸۲۰۰ ۰۰۰۰ ۰۰۰۰ ۰۰۰۰ ۰۰۰۰"
              style={{
                flex: 1, minWidth: 0,
                border: 'none', outline: 'none', background: 'transparent',
                fontSize: 14, fontWeight: 600,
                fontFamily: 'JetBrains Mono, ui-monospace, monospace',
                fontVariantNumeric: 'tabular-nums',
                color: 'var(--ink)',
                letterSpacing: '0.05em',
                direction: 'ltr', textAlign: 'left',
              }}
            />
            {ibanComplete && (
              <span style={{
                color: 'var(--accent)',
                display: 'flex', alignItems: 'center',
              }}>
                <window.IconCheck size={18} color="currentColor" />
              </span>
            )}
          </div>
          <div style={{
            marginTop: 8, fontSize: 10.5,
            color: ibanInvalid ? 'var(--danger)' : 'var(--muted)',
            display: 'flex', justifyContent: 'space-between',
          }}>
            <span>{ibanInvalid ? 'شماره شبا باید دقیقاً ۲۴ رقم باشد' : 'شماره شبا روی کارت بانکی شما درج شده است'}</span>
            <span style={{
              fontFamily: 'JetBrains Mono, ui-monospace, monospace',
              fontVariantNumeric: 'tabular-nums',
            }}>{faNumD(ibanDigits.length)}/۲۴</span>
          </div>
        </div>

        {/* note */}
        <div style={{
          marginTop: 14,
          padding: '10px 12px',
          background: 'color-mix(in oklab, var(--accent) 6%, transparent)',
          border: '1px solid color-mix(in oklab, var(--accent) 25%, transparent)',
          borderRadius: 12,
          fontSize: 11.5, lineHeight: 1.6,
          color: 'var(--ink)',
          display: 'flex', gap: 10, alignItems: 'flex-start',
        }}>
          <span style={{
            flexShrink: 0, width: 18, height: 18, borderRadius: 99,
            background: 'var(--accent)', color: '#fff',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 11, fontWeight: 700, marginTop: 1,
          }}>i</span>
          <span>
            مدارک ارسالی برای تایید توسط واحد منابع انسانی بررسی می‌شود. اطلاعات شما نزد ما محفوظ است.
          </span>
        </div>
      </div>

      {/* sticky footer */}
      <div style={{
        flexShrink: 0,
        padding: '12px 18px 16px',
        background: 'var(--bg)',
        borderTop: '1px solid var(--border)',
        display: 'flex', alignItems: 'center', gap: 12,
      }}>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 11, color: 'var(--muted)' }}>
            {ready ? 'همه مدارک کامل است' : 'مدارک خود را تکمیل کنید'}
          </div>
          <div style={{
            fontSize: 14, fontWeight: 700,
            color: ready ? 'var(--accent)' : 'var(--ink)',
          }}>
            {faNumD(doneCount)} از {faNumD(3)} مورد
          </div>
        </div>
        <button
          disabled={!ready || submitted}
          onClick={handleSubmit}
          style={{
            all: 'unset', cursor: ready ? 'pointer' : 'not-allowed',
            padding: '13px 22px', borderRadius: 14,
            background: submitted
              ? 'color-mix(in oklab, var(--accent) 75%, #000)'
              : ready ? 'var(--accent)' : 'var(--icon-bg)',
            color: ready ? '#fff' : 'var(--muted)',
            fontSize: 14, fontWeight: 700,
            transition: 'background 180ms ease',
            minWidth: 110, textAlign: 'center',
          }}>
          {submitted ? '✓ ارسال شد' : 'ارسال مدارک'}
        </button>
      </div>
    </div>
  );
}

window.DocumentsScreen = DocumentsScreen;
