import { useState } from 'react';
import LogoMark from './LogoMark';

interface Props {
  onConnect: (url: string) => void;
  onLocalMode: () => void;
}

function normalizeUrl(raw: string): string {
  const trimmed = raw.trim().replace(/\/$/, '');
  if (!trimmed) return '';
  if (!/^https?:\/\//i.test(trimmed)) return 'https://' + trimmed;
  return trimmed;
}

function isValidUrl(url: string): boolean {
  try {
    const u = new URL(url);
    return u.protocol === 'http:' || u.protocol === 'https:';
  } catch {
    return false;
  }
}

// Plain http:// (to anything but loopback) sends the password in cleartext during
// the native login POST. Warn and require an explicit acknowledgement.
function isInsecureUrl(url: string): boolean {
  try {
    const u = new URL(url);
    if (u.protocol !== 'http:') return false;
    return !(u.hostname === 'localhost' || u.hostname === '127.0.0.1' || u.hostname === '::1');
  } catch {
    return false;
  }
}

const PhoneIcon = (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <rect x="6" y="2" width="12" height="20" rx="3" />
    <path d="M11 18h2" />
  </svg>
);

const ServerIcon = (
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <rect x="3" y="4" width="18" height="12" rx="2" />
    <path d="M8 20h8M12 16v4" />
  </svg>
);

export default function SetupScreen({ onConnect, onLocalMode }: Props) {
  const [mode, setMode] = useState<'choose' | 'server'>('choose');
  const [url, setUrl] = useState('');
  const [error, setError] = useState('');
  const [insecureAck, setInsecureAck] = useState(false);
  const [connecting, setConnecting] = useState(false);

  function handleConnect() {
    const normalized = normalizeUrl(url);
    if (!isValidUrl(normalized)) {
      setError('Enter a valid URL, e.g. https://bills.yourdomain.com');
      return;
    }
    // First tap on an insecure URL: warn and require a second, explicit tap.
    if (isInsecureUrl(normalized) && !insecureAck) {
      setError('');
      setInsecureAck(true);
      return;
    }
    setError('');
    setConnecting(true);
    onConnect(normalized);
  }

  function handleKey(e: React.KeyboardEvent) {
    if (e.key === 'Enter') handleConnect();
  }

  return (
    <div className="setup-root">
      <div className="setup-card">
        <div className="brand">
          <LogoMark />
          <div className="wordmark">Bill <b>Tracker</b></div>
          <p className="setup-subtitle">Calm command for household money.</p>
        </div>

        {mode === 'choose' ? (
          <>
            <div className="choices">
              {/* Local first: the simplest, most private option is one tap. */}
              <button type="button" className="door" onClick={onLocalMode}>
                <span className="door__icon">{PhoneIcon}</span>
                <span className="door__body">
                  <span className="door__title">Run on this phone</span>
                  <span className="door__desc">Private and offline. Nothing leaves your device.</span>
                </span>
                <span className="door__chev" aria-hidden="true">›</span>
              </button>

              <button
                type="button"
                className="door"
                onClick={() => { setMode('server'); setError(''); }}
              >
                <span className="door__icon">{ServerIcon}</span>
                <span className="door__body">
                  <span className="door__title">Connect to a server</span>
                  <span className="door__desc">Your self-hosted Bill Tracker.</span>
                </span>
                <span className="door__chev" aria-hidden="true">›</span>
              </button>
            </div>
            <p className="setup-footer">You can switch modes later by clearing the app's storage.</p>
          </>
        ) : (
          <>
            <div className="form-group">
              <label className="form-label" htmlFor="server-url">Server URL</label>
              <input
                id="server-url"
                className="form-input"
                type="url"
                inputMode="url"
                autoCapitalize="none"
                autoCorrect="off"
                spellCheck={false}
                placeholder="https://bills.yourdomain.com"
                value={url}
                onChange={e => { setUrl(e.target.value); setError(''); setInsecureAck(false); }}
                onKeyDown={handleKey}
                disabled={connecting}
                autoFocus
              />
              {error && <p className="form-error">{error}</p>}
              {insecureAck && (
                <p className="form-error">
                  This is an insecure <strong>http://</strong> address — your password will be sent
                  unencrypted. Only continue on a network you trust. Tap again to connect anyway.
                </p>
              )}
              <p className="form-hint">
                The address of your Bill Tracker server. Must be reachable from this device.
              </p>
            </div>

            <button
              className="btn-primary"
              onClick={handleConnect}
              disabled={connecting || !url.trim()}
            >
              {connecting ? 'Connecting…' : insecureAck ? 'Connect anyway' : 'Continue'}
            </button>
            <button
              className="btn-secondary"
              onClick={() => { setMode('choose'); setError(''); setInsecureAck(false); }}
              disabled={connecting}
            >
              Back
            </button>
          </>
        )}
      </div>
    </div>
  );
}
