/**
 * EncryptID Guardian Setup UI Component
 *
 * A web component for configuring social recovery guardians.
 * Designed to be embedded in any r-ecosystem app.
 */

import {
  Guardian,
  GuardianType,
  RecoveryConfig,
  getGuardianTypeInfo,
  getRecoveryManager,
} from '../recovery';

// ============================================================================
// STYLES
// ============================================================================

const styles = `
  :host {
    --eid-primary: #06b6d4;
    --eid-primary-hover: #0891b2;
    --eid-secondary: #f97316;
    --eid-success: #22c55e;
    --eid-warning: #eab308;
    --eid-danger: #ef4444;
    --eid-bg: #0f172a;
    --eid-bg-secondary: #1e293b;
    --eid-bg-tertiary: #334155;
    --eid-text: #f1f5f9;
    --eid-text-secondary: #94a3b8;
    --eid-border: #475569;
    --eid-radius: 8px;
    --eid-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.3);

    display: block;
    font-family: system-ui, -apple-system, sans-serif;
    color: var(--eid-text);
  }

  .guardian-setup {
    background: var(--eid-bg);
    border-radius: var(--eid-radius);
    padding: 24px;
    max-width: 600px;
  }

  .header {
    margin-bottom: 24px;
  }

  .header h2 {
    margin: 0 0 8px 0;
    font-size: 1.5rem;
    font-weight: 600;
  }

  .header p {
    margin: 0;
    color: var(--eid-text-secondary);
    font-size: 0.875rem;
  }

  .status-bar {
    display: flex;
    align-items: center;
    gap: 16px;
    padding: 16px;
    background: var(--eid-bg-secondary);
    border-radius: var(--eid-radius);
    margin-bottom: 24px;
  }

  .status-indicator {
    width: 12px;
    height: 12px;
    border-radius: 50%;
    flex-shrink: 0;
  }

  .status-indicator.configured {
    background: var(--eid-success);
    box-shadow: 0 0 8px var(--eid-success);
  }

  .status-indicator.incomplete {
    background: var(--eid-warning);
    box-shadow: 0 0 8px var(--eid-warning);
  }

  .status-indicator.not-configured {
    background: var(--eid-danger);
  }

  .status-text {
    flex: 1;
  }

  .status-text .label {
    font-weight: 500;
    margin-bottom: 2px;
  }

  .status-text .detail {
    font-size: 0.75rem;
    color: var(--eid-text-secondary);
  }

  .threshold-display {
    font-size: 1.25rem;
    font-weight: 600;
    color: var(--eid-primary);
  }

  .guardian-list {
    margin-bottom: 24px;
  }

  .guardian-card {
    display: flex;
    align-items: center;
    gap: 16px;
    padding: 16px;
    background: var(--eid-bg-secondary);
    border-radius: var(--eid-radius);
    margin-bottom: 12px;
    border: 1px solid var(--eid-border);
    transition: border-color 0.2s;
  }

  .guardian-card:hover {
    border-color: var(--eid-primary);
  }

  .guardian-icon {
    width: 48px;
    height: 48px;
    border-radius: 50%;
    background: var(--eid-bg-tertiary);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.25rem;
    flex-shrink: 0;
  }

  .guardian-info {
    flex: 1;
    min-width: 0;
  }

  .guardian-name {
    font-weight: 500;
    margin-bottom: 4px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .guardian-type {
    font-size: 0.75rem;
    color: var(--eid-text-secondary);
  }

  .guardian-verified {
    font-size: 0.625rem;
    color: var(--eid-success);
    margin-top: 4px;
  }

  .guardian-actions {
    display: flex;
    gap: 8px;
  }

  .btn {
    padding: 8px 16px;
    border-radius: var(--eid-radius);
    font-size: 0.875rem;
    font-weight: 500;
    border: none;
    cursor: pointer;
    transition: all 0.2s;
  }

  .btn-primary {
    background: var(--eid-primary);
    color: white;
  }

  .btn-primary:hover {
    background: var(--eid-primary-hover);
  }

  .btn-secondary {
    background: var(--eid-bg-tertiary);
    color: var(--eid-text);
    border: 1px solid var(--eid-border);
  }

  .btn-secondary:hover {
    background: var(--eid-border);
  }

  .btn-danger {
    background: transparent;
    color: var(--eid-danger);
    border: 1px solid var(--eid-danger);
  }

  .btn-danger:hover {
    background: var(--eid-danger);
    color: white;
  }

  .btn-icon {
    padding: 8px;
    width: 36px;
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .add-guardian-section {
    margin-top: 24px;
  }

  .add-guardian-section h3 {
    font-size: 1rem;
    font-weight: 500;
    margin: 0 0 16px 0;
  }

  .guardian-type-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    gap: 12px;
  }

  .guardian-type-card {
    padding: 16px;
    background: var(--eid-bg-secondary);
    border-radius: var(--eid-radius);
    border: 2px solid transparent;
    cursor: pointer;
    transition: all 0.2s;
    text-align: center;
  }

  .guardian-type-card:hover {
    border-color: var(--eid-primary);
  }

  .guardian-type-card.selected {
    border-color: var(--eid-primary);
    background: rgba(6, 182, 212, 0.1);
  }

  .guardian-type-icon {
    font-size: 2rem;
    margin-bottom: 8px;
  }

  .guardian-type-name {
    font-weight: 500;
    font-size: 0.875rem;
    margin-bottom: 4px;
  }

  .guardian-type-desc {
    font-size: 0.75rem;
    color: var(--eid-text-secondary);
  }

  .settings-section {
    margin-top: 24px;
    padding-top: 24px;
    border-top: 1px solid var(--eid-border);
  }

  .settings-section h3 {
    font-size: 1rem;
    font-weight: 500;
    margin: 0 0 16px 0;
  }

  .setting-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 0;
    border-bottom: 1px solid var(--eid-border);
  }

  .setting-row:last-child {
    border-bottom: none;
  }

  .setting-label {
    font-size: 0.875rem;
  }

  .setting-label .hint {
    font-size: 0.75rem;
    color: var(--eid-text-secondary);
    margin-top: 4px;
  }

  .setting-control {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .setting-control input[type="number"] {
    width: 60px;
    padding: 8px;
    border-radius: var(--eid-radius);
    border: 1px solid var(--eid-border);
    background: var(--eid-bg-secondary);
    color: var(--eid-text);
    text-align: center;
  }

  .setting-control select {
    padding: 8px 12px;
    border-radius: var(--eid-radius);
    border: 1px solid var(--eid-border);
    background: var(--eid-bg-secondary);
    color: var(--eid-text);
  }

  .modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.7);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
  }

  .modal {
    background: var(--eid-bg);
    border-radius: var(--eid-radius);
    padding: 24px;
    max-width: 400px;
    width: 90%;
    box-shadow: var(--eid-shadow);
  }

  .modal h3 {
    margin: 0 0 16px 0;
    font-size: 1.25rem;
  }

  .modal-actions {
    display: flex;
    gap: 12px;
    justify-content: flex-end;
    margin-top: 24px;
  }

  .form-group {
    margin-bottom: 16px;
  }

  .form-group label {
    display: block;
    font-size: 0.875rem;
    font-weight: 500;
    margin-bottom: 8px;
  }

  .form-group input {
    width: 100%;
    padding: 10px 12px;
    border-radius: var(--eid-radius);
    border: 1px solid var(--eid-border);
    background: var(--eid-bg-secondary);
    color: var(--eid-text);
    font-size: 0.875rem;
    box-sizing: border-box;
  }

  .form-group input:focus {
    outline: none;
    border-color: var(--eid-primary);
  }

  .empty-state {
    text-align: center;
    padding: 32px;
    color: var(--eid-text-secondary);
  }

  .empty-state-icon {
    font-size: 3rem;
    margin-bottom: 16px;
  }

  @keyframes pulse {
    0%, 100% { opacity: 1; }
    50% { opacity: 0.5; }
  }

  .loading {
    animation: pulse 1.5s infinite;
  }
`;

// ============================================================================
// ICONS (simple SVG paths)
// ============================================================================

const ICONS: Record<string, string> = {
  key: '🔑',
  user: '👤',
  shield: '🛡️',
  building: '🏢',
  clock: '⏰',
  check: '✓',
  x: '✕',
  plus: '+',
  trash: '🗑️',
  refresh: '↻',
  question: '?',
};

// ============================================================================
// WEB COMPONENT
// ============================================================================

export class GuardianSetupElement extends HTMLElement {
  private shadow: ShadowRoot;
  private config: RecoveryConfig | null = null;
  private selectedType: GuardianType | null = null;
  private showAddModal: boolean = false;

  constructor() {
    super();
    this.shadow = this.attachShadow({ mode: 'open' });
  }

  connectedCallback() {
    this.loadConfig();
  }

  private async loadConfig() {
    const manager = getRecoveryManager();

    // Ensure server sync is complete before reading config
    await manager.ensureLoaded();
    this.config = manager.getConfig();

    // Initialize if not configured
    if (!this.config) {
      await manager.initializeRecovery(3);
      this.config = manager.getConfig();
    }

    this.render();
  }

  private render() {
    const totalWeight = this.config?.guardians.reduce((sum, g) => sum + g.weight, 0) ?? 0;
    const threshold = this.config?.threshold ?? 3;
    const isConfigured = totalWeight >= threshold;
    const guardians = this.config?.guardians ?? [];

    this.shadow.innerHTML = `
      <style>${styles}</style>
      <div class="guardian-setup">
        <div class="header">
          <h2>🛡️ Social Recovery</h2>
          <p>Set up guardians to recover your account without seed phrases</p>
        </div>

        <div class="status-bar">
          <div class="status-indicator ${isConfigured ? 'configured' : totalWeight > 0 ? 'incomplete' : 'not-configured'}"></div>
          <div class="status-text">
            <div class="label">${isConfigured ? 'Recovery Configured' : 'Setup Incomplete'}</div>
            <div class="detail">
              ${isConfigured
                ? `${threshold} of ${guardians.length} guardians needed to recover`
                : `Add ${threshold - totalWeight} more guardian${threshold - totalWeight > 1 ? 's' : ''} to enable recovery`
              }
            </div>
          </div>
          <div class="threshold-display">${totalWeight}/${threshold}</div>
        </div>

        <div class="guardian-list">
          ${guardians.length === 0 ? `
            <div class="empty-state">
              <div class="empty-state-icon">🛡️</div>
              <p>No guardians configured yet</p>
              <p style="font-size: 0.875rem; margin-top: 8px;">Add guardians below to enable account recovery</p>
            </div>
          ` : guardians.map(g => this.renderGuardianCard(g)).join('')}
        </div>

        <div class="add-guardian-section">
          <h3>Add a Guardian</h3>
          <div class="guardian-type-grid">
            ${this.renderGuardianTypes()}
          </div>
        </div>

        <div class="settings-section">
          <h3>Recovery Settings</h3>

          <div class="setting-row">
            <div class="setting-label">
              <div>Required Guardians</div>
              <div class="hint">How many guardians must approve recovery</div>
            </div>
            <div class="setting-control">
              <input type="number" id="threshold" value="${threshold}" min="1" max="7">
              <span>of ${guardians.length}</span>
            </div>
          </div>

          <div class="setting-row">
            <div class="setting-label">
              <div>Time Lock</div>
              <div class="hint">Waiting period before recovery completes</div>
            </div>
            <div class="setting-control">
              <select id="delay">
                <option value="3600" ${this.config?.delaySeconds === 3600 ? 'selected' : ''}>1 hour</option>
                <option value="86400" ${this.config?.delaySeconds === 86400 ? 'selected' : ''}>24 hours</option>
                <option value="172800" ${this.config?.delaySeconds === 172800 ? 'selected' : ''}>48 hours</option>
                <option value="604800" ${this.config?.delaySeconds === 604800 ? 'selected' : ''}>7 days</option>
              </select>
            </div>
          </div>
        </div>

        ${this.showAddModal ? this.renderAddModal() : ''}
      </div>
    `;

    this.attachEventListeners();
  }

  private renderGuardianCard(guardian: Guardian): string {
    const typeInfo = getGuardianTypeInfo(guardian.type);
    const verified = guardian.lastVerified
      ? `Verified ${this.formatTimeAgo(guardian.lastVerified)}`
      : 'Not verified';

    return `
      <div class="guardian-card" data-guardian-id="${guardian.id}">
        <div class="guardian-icon">${ICONS[typeInfo.icon]}</div>
        <div class="guardian-info">
          <div class="guardian-name">${guardian.name}</div>
          <div class="guardian-type">${typeInfo.name}</div>
          <div class="guardian-verified">${guardian.lastVerified ? '✓ ' : ''}${verified}</div>
        </div>
        <div class="guardian-actions">
          <button class="btn btn-secondary btn-icon verify-btn" title="Verify">
            ${ICONS.refresh}
          </button>
          <button class="btn btn-danger btn-icon remove-btn" title="Remove">
            ${ICONS.trash}
          </button>
        </div>
      </div>
    `;
  }

  private renderGuardianTypes(): string {
    const types = [
      GuardianType.SECONDARY_PASSKEY,
      GuardianType.TRUSTED_CONTACT,
      GuardianType.HARDWARE_KEY,
      GuardianType.INSTITUTIONAL,
      GuardianType.TIME_DELAYED_SELF,
    ];

    return types.map(type => {
      const info = getGuardianTypeInfo(type);
      const isSelected = this.selectedType === type;

      return `
        <div class="guardian-type-card ${isSelected ? 'selected' : ''}" data-type="${type}">
          <div class="guardian-type-icon">${ICONS[info.icon]}</div>
          <div class="guardian-type-name">${info.name}</div>
          <div class="guardian-type-desc">${info.description}</div>
        </div>
      `;
    }).join('');
  }

  private renderAddModal(): string {
    if (!this.selectedType) return '';

    const info = getGuardianTypeInfo(this.selectedType);

    return `
      <div class="modal-overlay">
        <div class="modal">
          <h3>Add ${info.name}</h3>
          <p style="color: var(--eid-text-secondary); font-size: 0.875rem; margin-bottom: 16px;">
            ${info.setupInstructions}
          </p>

          <div class="form-group">
            <label for="guardian-name">Guardian Name</label>
            <input type="text" id="guardian-name" placeholder="e.g., My YubiKey, Mom's Account">
          </div>

          ${this.selectedType === GuardianType.TRUSTED_CONTACT ? `
            <div class="form-group">
              <label for="guardian-email">Contact Email</label>
              <input type="email" id="guardian-email" placeholder="friend@example.com">
            </div>
          ` : ''}

          ${this.selectedType === GuardianType.TIME_DELAYED_SELF ? `
            <div class="form-group">
              <label for="guardian-delay">Recovery Delay</label>
              <select id="guardian-delay" style="width: 100%; padding: 10px; border-radius: var(--eid-radius); border: 1px solid var(--eid-border); background: var(--eid-bg-secondary); color: var(--eid-text);">
                <option value="604800">7 days</option>
                <option value="1209600">14 days</option>
                <option value="2592000">30 days</option>
              </select>
            </div>
          ` : ''}

          <div class="modal-actions">
            <button class="btn btn-secondary" id="cancel-add">Cancel</button>
            <button class="btn btn-primary" id="confirm-add">Add Guardian</button>
          </div>
        </div>
      </div>
    `;
  }

  private attachEventListeners() {
    // Guardian type selection
    this.shadow.querySelectorAll('.guardian-type-card').forEach(card => {
      card.addEventListener('click', () => {
        const type = card.getAttribute('data-type') as GuardianType;
        this.selectedType = type;
        this.showAddModal = true;
        this.render();
      });
    });

    // Guardian card actions
    this.shadow.querySelectorAll('.guardian-card').forEach(card => {
      const id = card.getAttribute('data-guardian-id');

      card.querySelector('.verify-btn')?.addEventListener('click', (e) => {
        e.stopPropagation();
        this.verifyGuardian(id!);
      });

      card.querySelector('.remove-btn')?.addEventListener('click', (e) => {
        e.stopPropagation();
        this.removeGuardian(id!);
      });
    });

    // Modal actions
    this.shadow.getElementById('cancel-add')?.addEventListener('click', () => {
      this.showAddModal = false;
      this.selectedType = null;
      this.render();
    });

    this.shadow.getElementById('confirm-add')?.addEventListener('click', () => {
      this.addGuardian();
    });

    // Settings
    this.shadow.getElementById('threshold')?.addEventListener('change', (e) => {
      const value = parseInt((e.target as HTMLInputElement).value);
      getRecoveryManager().setThreshold(value).then(() => {
        this.loadConfig();
        this.render();
      });
    });

    this.shadow.getElementById('delay')?.addEventListener('change', (e) => {
      const value = parseInt((e.target as HTMLSelectElement).value);
      getRecoveryManager().setDelay(value).then(() => {
        this.loadConfig();
        this.render();
      });
    });

    // Close modal on overlay click
    this.shadow.querySelector('.modal-overlay')?.addEventListener('click', (e) => {
      if (e.target === e.currentTarget) {
        this.showAddModal = false;
        this.selectedType = null;
        this.render();
      }
    });
  }

  private async addGuardian() {
    if (!this.selectedType) return;

    const nameInput = this.shadow.getElementById('guardian-name') as HTMLInputElement;
    const emailInput = this.shadow.getElementById('guardian-email') as HTMLInputElement;
    const delayInput = this.shadow.getElementById('guardian-delay') as HTMLSelectElement;

    const name = nameInput?.value.trim();
    if (!name) {
      alert('Please enter a name for this guardian');
      return;
    }

    const guardian: Omit<Guardian, 'id' | 'addedAt'> = {
      type: this.selectedType,
      name,
      weight: 1,
    };

    if (this.selectedType === GuardianType.TRUSTED_CONTACT && emailInput) {
      guardian.contactEmail = emailInput.value.trim();
    }

    if (this.selectedType === GuardianType.TIME_DELAYED_SELF && delayInput) {
      guardian.delaySeconds = parseInt(delayInput.value);
    }

    try {
      await getRecoveryManager().addGuardian(guardian);
      this.showAddModal = false;
      this.selectedType = null;
      this.loadConfig();
      this.render();

      // Dispatch event
      this.dispatchEvent(new CustomEvent('guardian-added', { detail: guardian }));
    } catch (error) {
      alert(`Failed to add guardian: ${error}`);
    }
  }

  private async verifyGuardian(id: string) {
    try {
      await getRecoveryManager().verifyGuardian(id);
      this.loadConfig();
      this.render();

      this.dispatchEvent(new CustomEvent('guardian-verified', { detail: { id } }));
    } catch (error) {
      alert(`Failed to verify guardian: ${error}`);
    }
  }

  private async removeGuardian(id: string) {
    if (!confirm('Are you sure you want to remove this guardian?')) {
      return;
    }

    try {
      await getRecoveryManager().removeGuardian(id);
      this.loadConfig();
      this.render();

      this.dispatchEvent(new CustomEvent('guardian-removed', { detail: { id } }));
    } catch (error) {
      alert(`Failed to remove guardian: ${error}`);
    }
  }

  private formatTimeAgo(timestamp: number): string {
    const seconds = Math.floor((Date.now() - timestamp) / 1000);

    if (seconds < 60) return 'just now';
    if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
    if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
    return `${Math.floor(seconds / 86400)}d ago`;
  }
}

// Register the custom element
customElements.define('encryptid-guardian-setup', GuardianSetupElement);
