const KEY = 'shire_dental_license_v1';
const INSTALL_KEY = 'shire_dental_install_v1';
const TRIAL_DAYS = 14;

const now = () => Date.now();
const read = (key) => { try { return JSON.parse(localStorage.getItem(key) || 'null'); } catch { return null; } };
const write = (key, value) => localStorage.setItem(key, JSON.stringify(value));

export function getInstallation() {
  let install = read(INSTALL_KEY);
  if (!install) { install = { id: crypto.randomUUID?.() || `install-${now()}`, installedAt: now() }; write(INSTALL_KEY, install); }
  return install;
}

export function getLicenseStatus(mode = 'standalone') {
  if (mode === 'shire') return { active: true, plan: 'SHiRE OS', source: 'shire', expiresAt: null };
  const license = read(KEY);
  if (license?.active && (!license.expiresAt || license.expiresAt > now())) return license;
  const install = getInstallation();
  const expiresAt = install.installedAt + TRIAL_DAYS * 86400000;
  return { active: expiresAt > now(), trial: true, plan: 'Professional Trial', expiresAt, daysRemaining: Math.max(0, Math.ceil((expiresAt-now())/86400000)) };
}

export function activateLicense(key) {
  const clean = String(key || '').trim().toUpperCase();
  // Offline development keys. Replace with signed server verification before commercial release.
  const match = clean.match(/^SHIRE-DENTAL-(PRO|ANNUAL|LIFETIME)-([A-Z0-9]{8,})$/);
  if (!match) throw new Error('That activation key is not valid.');
  const plan = match[1];
  const expiresAt = plan === 'LIFETIME' ? null : now() + (plan === 'ANNUAL' ? 365 : 30) * 86400000;
  const license = { active: true, plan, keyLast4: clean.slice(-4), activatedAt: now(), expiresAt, source: 'offline-development' };
  write(KEY, license); return license;
}

export function deactivateLicense() { localStorage.removeItem(KEY); }
