'use client';

/**
 * TeamCreateOrg — create the org this account will own. Mirrors the onboarding
 * create flow but lives inline in /settings/team so the whole setup happens in
 * one place. On success the page revalidates to show the org + members.
 */

import { useState } from 'react';
import { useRouter } from 'next/navigation';

function slugify(name) {
  return (
    name.trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60) || 'org'
  );
}

export default function TeamCreateOrg() {
  const router = useRouter();
  const [name, setName] = useState('');
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState('');

  async function createOrg(e) {
    e.preventDefault();
    setError('');
    setBusy(true);
    try {
      const res = await fetch('/api/orgs', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: name.trim(), slug: slugify(name) }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(data.error || 'Could not create organization.');
      router.refresh();
    } catch (err) {
      setError(err.message);
    } finally {
      setBusy(false);
    }
  }

  return (
    <form onSubmit={createOrg} style={{ display: 'grid', gap: '0.75rem' }}>
      <p className="admin-muted" style={{ margin: 0, fontSize: '0.9em' }}>
        Start fresh — you'll be the owner. You can invite teammates once it exists.
      </p>
      <label className="admin-field">
        <span>Organization name</span>
        <input
          className="admin-input"
          value={name}
          onChange={(e) => setName(e.target.value)}
          placeholder="Acme Robotics"
          required
          autoComplete="off"
        />
      </label>
      {name.trim() ? (
        <p className="admin-muted" style={{ margin: 0, fontSize: '0.78em' }}>
          Slug: <code className="mono">{slugify(name)}</code>
        </p>
      ) : null}
      {error ? (
        <div role="alert" style={{ color: 'var(--accent-600)', fontSize: '0.85em' }}>{error}</div>
      ) : null}
      <div className="admin-form-actions">
        <button type="submit" className="admin-btn-primary" disabled={busy || !name.trim()}>
          {busy ? 'Creating…' : 'Create organization'}
        </button>
      </div>
    </form>
  );
}
