// Partial early repayment screen — Komek Lombard v2
// Mirrors the "Условия пролонгации" screen pattern, but with an editable amount.

const PR_TEAL = '#1B7F70';
const PR_TEAL_DEEP = '#176A5D';
const PR_BORDER = '#E2E2E5';
const PR_LABEL = '#0B0B0C';
const PR_BODY = '#3A3A3D';
const PR_HINT = '#9A9AA0';

// ─── icons ─────────────────────────────────────────────────────────
const PRIcon = {
  arrowLeft: (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
      <path d="M15 5l-7 7 7 7" stroke="#0B0B0C" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  ),
  chevron: (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
      <path d="M9 6l6 6-6 6" stroke="#8A8A8E" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  ),
  wallet: (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
      <rect x="2.5" y="6.5" width="19" height="13" rx="3" stroke="#3A3A3D" strokeWidth="1.6"/>
      <path d="M2.5 10h19" stroke="#3A3A3D" strokeWidth="1.6"/>
      <circle cx="17" cy="14.5" r="1.2" fill="#3A3A3D"/>
    </svg>
  ),
  tenge: (
    <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
      <circle cx="12" cy="12" r="9.2" stroke="#3A3A3D" strokeWidth="1.6"/>
      <path d="M7.5 8h9M7.5 11.2h9M12 11.2V17" stroke="#3A3A3D" strokeWidth="1.7" strokeLinecap="round"/>
    </svg>
  ),
  check: (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
      <path d="M5 12.5l4.5 4.5L19 7.5" stroke="#fff" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"/>
    </svg>
  ),
};

// ─── top bar ───────────────────────────────────────────────────────
function TopBar({ title, onBack }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 8,
      padding: '4px 16px 14px',
      minHeight: 44,
    }}>
      <button onClick={onBack} aria-label="Назад" style={{
        width: 36, height: 36, borderRadius: 18, border: 'none',
        background: 'transparent', cursor: 'pointer',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 0, flexShrink: 0,
      }}>{PRIcon.arrowLeft}</button>
      <div style={{
        flex: 1, textAlign: 'center',
        fontSize: 17, fontWeight: 700, color: '#0B0B0C',
        letterSpacing: -0.2, paddingRight: 36, lineHeight: 1.2,
      }}>{title}</div>
    </div>
  );
}

// ─── field ─────────────────────────────────────────────────────────
function FieldLabel({ children }) {
  return (
    <div style={{
      fontSize: 16, fontWeight: 700, color: PR_LABEL,
      margin: '4px 4px 8px',
    }}>{children}</div>
  );
}

function MethodSelector({ value, onClick }) {
  return (
    <button onClick={onClick} style={{
      width: '100%', height: 56, borderRadius: 14,
      border: `1.5px solid ${PR_BORDER}`, background: '#fff',
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '0 14px', cursor: 'pointer',
      fontFamily: 'inherit',
    }}>
      {PRIcon.wallet}
      <span style={{
        flex: 1, textAlign: 'left',
        fontSize: 16, color: value ? PR_LABEL : PR_HINT,
        fontWeight: value ? 600 : 500,
      }}>{value || 'Выбрать метод оплаты'}</span>
      {PRIcon.chevron}
    </button>
  );
}

function AmountInput({ value, onChange, max }) {
  const display = value === '' ? '' : Number(value).toLocaleString('ru-RU');
  return (
    <div style={{
      width: '100%', height: 56, borderRadius: 14,
      border: `1.5px solid ${PR_BORDER}`, background: '#fff',
      display: 'flex', alignItems: 'center', gap: 12,
      padding: '0 14px',
    }}>
      {PRIcon.tenge}
      <input
        inputMode="numeric"
        value={display}
        onChange={(e) => {
          const digits = e.target.value.replace(/\D/g, '');
          if (digits === '') { onChange(''); return; }
          const n = parseInt(digits, 10);
          onChange(Math.min(n, max));
        }}
        placeholder="0"
        style={{
          flex: 1, border: 'none', outline: 'none', background: 'transparent',
          fontSize: 17, fontWeight: 700, color: PR_LABEL,
          fontFamily: 'inherit', minWidth: 0,
        }}
      />
      <span style={{ fontSize: 17, fontWeight: 700, color: PR_LABEL }}>₸</span>
    </div>
  );
}

function HelperRow({ left, right }) {
  return (
    <div style={{
      display: 'flex', justifyContent: 'space-between',
      padding: '8px 6px 0', fontSize: 13, color: PR_HINT,
    }}>
      <span>{left}</span>
      <span>{right}</span>
    </div>
  );
}

function Checkbox({ checked, onChange, children }) {
  return (
    <label style={{
      display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer',
      padding: '4px 2px',
    }}>
      <span style={{
        width: 22, height: 22, borderRadius: 6, flexShrink: 0,
        background: checked ? PR_TEAL : '#fff',
        border: checked ? 'none' : `1.5px solid #C8C8CC`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        transition: 'background 120ms ease',
      }}>
        {checked && PRIcon.check}
      </span>
      <input
        type="checkbox" checked={checked}
        onChange={(e) => onChange(e.target.checked)}
        style={{ position: 'absolute', opacity: 0, pointerEvents: 'none' }}
      />
      <span style={{ fontSize: 14.5, color: PR_BODY, fontWeight: 500 }}>{children}</span>
    </label>
  );
}

function PayButton({ enabled, children, onClick }) {
  return (
    <button onClick={enabled ? onClick : undefined} style={{
      width: '100%', height: 56, borderRadius: 12, border: 'none',
      background: enabled ? PR_TEAL : '#C9DAD6',
      color: '#fff', fontSize: 17, fontWeight: 700,
      letterSpacing: 0.1, fontFamily: 'inherit',
      cursor: enabled ? 'pointer' : 'not-allowed',
      transition: 'background 150ms ease',
    }}>{children}</button>
  );
}

// ─── screen ────────────────────────────────────────────────────────
// Default pledged items for a multi-item ticket. minRemainder is the BP-2 min.
// balance for each item; a single repayment must keep at least that much in debt.
const DEFAULT_ITEMS = [
  { id: 'i1', name: 'Часы Rolex Datejust',     balance: 18000, minRemainder: 5000 },
  { id: 'i2', name: 'Кольцо золотое 585°',  balance: 14000, minRemainder: 5000 },
  { id: 'i3', name: 'Серьги серебряные',  balance:  8000, minRemainder: 5000 },
];

function itemMaxRepayable(it) {
  return Math.max(0, it.balance - it.minRemainder);
}

function distributeAllocations({ items, modes, manualValues, total }) {
  // total = budget that goes specifically to main debt (already excludes interest)
  const result = {};
  let manualSum = 0;
  items.forEach(it => {
    if (modes[it.id] === 'manual') {
      const v = Math.max(0, Math.min(manualValues[it.id] || 0, itemMaxRepayable(it)));
      result[it.id] = v;
      manualSum += v;
    }
  });
  const autoItems = items.filter(it => modes[it.id] === 'auto');
  const autoBudget = Math.max(0, total - manualSum);
  const autoBase = autoItems.reduce((s, it) => s + itemMaxRepayable(it), 0);
  let assigned = 0;
  autoItems.forEach((it, idx) => {
    const cap = itemMaxRepayable(it);
    if (autoBase === 0 || autoBudget === 0) {
      result[it.id] = 0;
    } else if (idx === autoItems.length - 1) {
      result[it.id] = Math.max(0, Math.min(cap, autoBudget - assigned));
    } else {
      const v = Math.min(cap, Math.round((cap / autoBase) * autoBudget));
      result[it.id] = v;
      assigned += v;
    }
  });
  return { result, manualSum };
}

function ToggleSwitch({ checked, onChange }) {
  return (
    <button onClick={() => onChange(!checked)} aria-pressed={checked} style={{
      width: 42, height: 26, borderRadius: 999, border: 'none', padding: 0, cursor: 'pointer',
      background: checked ? PR_TEAL : '#D5D6DA',
      transition: 'background 150ms ease', position: 'relative',
      flexShrink: 0,
    }}>
      <span style={{
        position: 'absolute', top: 3, left: checked ? 19 : 3,
        width: 20, height: 20, borderRadius: '50%', background: '#fff',
        transition: 'left 150ms ease',
        boxShadow: '0 1px 3px rgba(0,0,0,0.2)',
      }}/>
    </button>
  );
}

function ItemAllocationRow({ item, mode, value, onMode, onChange, isFirst, isLast }) {
  const cap = itemMaxRepayable(item);
  const editing = mode === 'manual';
  const atCap = editing && (value || 0) >= cap && cap > 0;
  const valueColor = editing ? PR_LABEL : '#5C5C60';
  return (
    <div style={{
      padding: '14px 14px',
      background: '#fff',
      borderTop: isFirst ? 'none' : `1px solid ${PR_BORDER}`,
      display: 'flex', flexDirection: 'column', gap: 10,
    }}>
      {/* header: title + toggle */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
        <div style={{
          flex: 1, minWidth: 0,
          fontSize: 15, fontWeight: 500, color: PR_LABEL, lineHeight: 1.3,
          overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
        }}>{item.name}</div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0 }}>
          <span style={{
            fontSize: 12.5, fontWeight: 600,
            color: editing ? PR_LABEL : PR_HINT,
          }}>Изменить</span>
          <ToggleSwitch checked={editing} onChange={(c) => onMode(c ? 'manual' : 'auto')}/>
        </div>
      </div>

      {/* Amount field — same shape as main AmountInput; disabled when auto */}
      <div style={{
        width: '100%', height: 56, borderRadius: 14, boxSizing: 'border-box',
        border: `1.5px solid ${editing ? PR_TEAL : PR_BORDER}`,
        background: editing ? '#fff' : '#F4F5F7',
        boxShadow: editing ? '0 0 0 4px rgba(27,127,112,0.08)' : 'none',
        display: 'flex', alignItems: 'center', gap: 12,
        padding: '0 14px',
        transition: 'background 120ms ease, border-color 120ms ease',
      }}>
        <span style={{ opacity: editing ? 1 : 0.55, display: 'inline-flex' }}>
          {PRIcon.tenge}
        </span>
        <input
          type="text" inputMode="numeric"
          value={(value || 0).toLocaleString('ru-RU')}
          readOnly={!editing}
          tabIndex={editing ? 0 : -1}
          onChange={(e) => {
            if (!editing) return;
            const digits = e.target.value.replace(/\D/g, '');
            onChange(digits === '' ? 0 : parseInt(digits, 10));
          }}
          style={{
            flex: 1, minWidth: 0, border: 'none', outline: 'none', background: 'transparent',
            fontFamily: 'inherit', fontSize: 17, fontWeight: 700,
            color: valueColor,
            cursor: editing ? 'text' : 'default',
          }}
        />
        <span style={{ fontSize: 17, fontWeight: 700, color: valueColor }}>₸</span>
      </div>

      {/* Info below the field */}
      <div style={{
        fontSize: 12, color: atCap ? '#A8312B' : PR_HINT,
        fontWeight: atCap ? 600 : 400,
        padding: '0 4px', lineHeight: 1.4,
      }}>
        {atCap
          ? `Достигнут максимум: ${cap.toLocaleString('ru-RU')} ₸`
          : `Долг ${item.balance.toLocaleString('ru-RU')} ₸ · мин. остаток ${item.minRemainder.toLocaleString('ru-RU')} ₸`
        }
      </div>
    </div>
  );
}

// ─── screen ─────────────────────────────────────────────────────
function PartialRepaymentScreen({ onBack, loanBalance = 40000, accruedInterest = 1234, minAmount = 5000, maxAmount = 35000, items = DEFAULT_ITEMS, initialAmount = 0, initialMethod = '', initialAgreed = false, initialAllocations }) {
  const [method, setMethod] = React.useState(initialMethod);
  const [amount, setAmount] = React.useState(initialAmount);
  const [agreed, setAgreed] = React.useState(initialAgreed);

  // per-item mode + manual values
  const [modes, setModes] = React.useState(() => Object.fromEntries(
    items.map(it => [it.id, (initialAllocations && initialAllocations[it.id] && initialAllocations[it.id].mode) || 'auto'])
  ));
  const [manualValues, setManualValues] = React.useState(() => Object.fromEntries(
    items.map(it => [it.id, (initialAllocations && initialAllocations[it.id] && initialAllocations[it.id].value) || 0])
  ));

  const debtBudget = Math.max(0, Number(amount || 0) - accruedInterest);
  const { result: alloc, manualSum } = distributeAllocations({
    items, modes, manualValues, total: debtBudget,
  });
  const manualOver = manualSum > debtBudget;

  const max = maxAmount;
  const valid = method !== '' && Number(amount) >= minAmount && Number(amount) <= max && agreed && !manualOver;

  const setItemMode = (id, m) => {
    setModes(prev => ({ ...prev, [id]: m }));
    if (m === 'manual') {
      // when switching to manual, seed the field with the current auto allocation
      setManualValues(prev => ({ ...prev, [id]: alloc[id] || 0 }));
    }
  };
  const setItemManual = (id, v) => {
    const item = items.find(it => it.id === id);
    const cap = itemMaxRepayable(item);
    setManualValues(prev => ({ ...prev, [id]: Math.min(cap, Math.max(0, v)) }));
  };

  return (
    <div style={{
      height: '100%', background: '#fff',
      fontFamily: '-apple-system, "SF Pro Text", system-ui, sans-serif',
      WebkitFontSmoothing: 'antialiased',
      paddingTop: 56,
      display: 'flex', flexDirection: 'column', overflow: 'hidden',
      boxSizing: 'border-box',
    }}>
      <TopBar title="Частичное погашение" onBack={onBack}/>

      {/* scrollable middle */}
      <div style={{
        flex: 1, minHeight: 0, overflowY: 'auto',
        padding: '4px 20px 8px',
      }}>
        {/* description */}
        <p style={{
          margin: '2px 0 16px', fontSize: 15, lineHeight: 1.4,
          color: PR_BODY, fontWeight: 400,
        }}>
          Укажите сумму частичного погашения — она спишется в счёт начисленных процентов, а остаток уменьшит основной долг.<br/>
          Проценты пересчитаются автоматически.
        </p>

        {/* method */}
        <FieldLabel>Метод оплаты</FieldLabel>
        <MethodSelector value={method} onClick={() => setMethod('Mastercard •••• 4783')}/>

        {/* amount */}
        <div style={{ height: 14 }}/>
        <FieldLabel>Частично погашаю сейчас</FieldLabel>
        <AmountInput value={amount} onChange={setAmount} max={max}/>
        <div style={{
          padding: '8px 6px 0', fontSize: 13, color: PR_HINT,
          textAlign: 'left',
        }}>
          Максимальная сумма к погашению {max.toLocaleString('ru-RU')} ₸
        </div>

        {/* secondary info — less important than the payment summary */}
        <div style={{
          marginTop: 14, padding: '0 4px',
          display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 12,
          fontSize: 13,
        }}>
          <span style={{ color: PR_HINT, flex: 1, minWidth: 0 }}>Сумма кредита до частичного погашения</span>
          <span style={{ color: PR_HINT, fontWeight: 600, whiteSpace: 'nowrap' }}>
            {loanBalance.toLocaleString('ru-RU')} ₸
          </span>
        </div>
        <div style={{
          marginTop: 4, padding: '0 4px',
          display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 12,
          fontSize: 13,
        }}>
          <span style={{ color: PR_HINT, flex: 1, minWidth: 0 }}>Сумма кредита после частичного погашения</span>
          <span style={{ color: PR_HINT, fontWeight: 600, whiteSpace: 'nowrap' }}>
            {Math.max(0, loanBalance - Math.max(0, Number(amount || 0) - accruedInterest)).toLocaleString('ru-RU')} ₸
          </span>
        </div>

        {/* summary preview */}
        <div style={{
          marginTop: 14, padding: '12px 14px',
          background: '#F4F7F6', borderRadius: 12,
          display: 'flex', flexDirection: 'column', gap: 6,
        }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 12, fontSize: 14 }}>
            <span style={{ color: PR_BODY, flex: 1, minWidth: 0 }}>Сумма процентов</span>
            <span style={{ color: PR_LABEL, fontWeight: 700, whiteSpace: 'nowrap' }}>
              {Math.min(Number(amount || 0), accruedInterest).toLocaleString('ru-RU')} ₸
            </span>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 12, fontSize: 14 }}>
            <span style={{ color: PR_BODY, flex: 1, minWidth: 0 }}>Сумма погашения основного долга</span>
            <span style={{ color: PR_LABEL, fontWeight: 700, whiteSpace: 'nowrap' }}>
              {Math.max(0, Number(amount || 0) - accruedInterest).toLocaleString('ru-RU')} ₸
            </span>
          </div>
          <div style={{ height: 1, background: '#E2E8E6', margin: '2px 0' }}/>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 12, fontSize: 14.5 }}>
            <span style={{ color: PR_TEAL_DEEP, fontWeight: 600, flex: 1, minWidth: 0 }}>Будет выполнен платёж</span>
            <span style={{ color: PR_TEAL_DEEP, fontWeight: 800, whiteSpace: 'nowrap' }}>
              {Number(amount || 0).toLocaleString('ru-RU')} ₸
            </span>
          </div>
        </div>

        {/* Items — per-item allocation (placed right before the footer) */}
        <div style={{ marginTop: 18 }}>
          <div style={{
            display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
            marginBottom: 4,
          }}>
            <FieldLabel>Распределение по предметам</FieldLabel>
            <span style={{ fontSize: 12, color: PR_HINT }}>{items.length} предмета</span>
          </div>
          <div style={{
            border: `1px solid ${PR_BORDER}`, borderRadius: 14,
            background: '#fff', overflow: 'hidden',
          }}>
            {items.map((it, idx) => (
              <ItemAllocationRow
                key={it.id}
                item={it}
                mode={modes[it.id]}
                value={alloc[it.id]}
                isFirst={idx === 0}
                isLast={idx === items.length - 1}
                onMode={(m) => setItemMode(it.id, m)}
                onChange={(v) => setItemManual(it.id, v)}
              />
            ))}
          </div>
          {manualOver && (
            <div style={{
              marginTop: 10, padding: '10px 12px', borderRadius: 10,
              background: '#FBE9E8', color: '#A8312B',
              fontSize: 12.5, lineHeight: 1.4,
            }}>
              Сумма ручных распределений ({manualSum.toLocaleString('ru-RU')} ₸) превышает сумму к распределению по основному долгу ({debtBudget.toLocaleString('ru-RU')} ₸). Уменьшите значения или увеличьте общую сумму платежа.
            </div>
          )}
        </div>

        <div style={{ flex: 1, minHeight: 4 }}/>
      </div>

      {/* fixed footer */}
      <div style={{
        flexShrink: 0, padding: '12px 20px 40px',
        background: '#fff',
        boxShadow: '0 -8px 16px -10px rgba(0,0,0,0.08)',
        display: 'flex', flexDirection: 'column', gap: 12,
      }}>
        <Checkbox checked={agreed} onChange={setAgreed}>
          Согласен(-на) с условиями частичного погашения
        </Checkbox>
        <PayButton enabled={valid}>Оплатить</PayButton>
      </div>
    </div>
  );
}

Object.assign(window, { PartialRepaymentScreen });
