import { useState, useEffect } from 'preact/hooks';
import { User, Buildings, Robot, X, CheckCircle, ArrowRight } from '@phosphor-icons/react';
import '../styles/palacejoin.css';

type Phase = 'splash' | 'ring' | 'complete' | 'welcome';
type CircleId = 'you' | 'palace' | 'butler';
type PalaceStyle = 'Classic' | 'Modern' | 'Minimal';
type ButlerTone = 'Sharp' | 'Friendly' | 'Formal';

interface AppData {
  you:    { name: string; tagline: string };
  palace: { name: string; style: PalaceStyle };
  butler: { name: string; tone: ButlerTone };
}

const META: Record<CircleId, { label: string; color: string; glow: string; delay: string }> = {
  you:    { label: 'You',          color: '#C9A84C', glow: 'rgba(201,168,76,0.42)',  delay: '0.12s' },
  palace: { label: 'Your Palace',  color: '#52A884', glow: 'rgba(82,168,132,0.42)',  delay: '0.28s' },
  butler: { label: 'Your Butler',  color: '#9E8CF0', glow: 'rgba(158,140,240,0.42)', delay: '0.18s' },
};

const CIRCLE_ICON: Record<CircleId, JSX.Element> = {
  you:    <User    size={28} weight="duotone" />,
  palace: <Buildings size={28} weight="duotone" />,
  butler: <Robot   size={28} weight="duotone" />,
};

const FORM_ICON: Record<CircleId, JSX.Element> = {
  you:    <User    size={38} weight="duotone" />,
  palace: <Buildings size={38} weight="duotone" />,
  butler: <Robot   size={38} weight="duotone" />,
};

const PALACE_CREST = (
  <svg viewBox="0 0 350 295" fill="none" xmlns="http://www.w3.org/2000/svg">
    <path d="M350 262.5C301.675 262.5 262.5 223.325 262.5 175" stroke="currentColor" stroke-width="65.625"/>
    <path d="M262.5 175C262.5 223.325 223.325 262.5 175 262.5" stroke="currentColor" stroke-width="65.625"/>
    <path d="M175 262.5C126.675 262.5 87.5 223.325 87.5 175" stroke="currentColor" stroke-width="65.625"/>
    <path d="M87.5 175C87.5 223.325 48.3249 262.5 0 262.5" stroke="currentColor" stroke-width="65.625"/>
    <path d="M87.5 175L87.5 0" stroke="currentColor" stroke-width="65.625"/>
    <path d="M262.5 175L262.5 0" stroke="currentColor" stroke-width="65.625"/>
    <path d="M0 120.312H350" stroke="currentColor" stroke-width="65.625"/>
  </svg>
);

// Circle centers in 360×340 SVG coordinate space
const CTR: Record<CircleId, [number, number]> = {
  you:    [180, 50],
  palace: [72,  237],
  butler: [288, 237],
};

export function JoinApp() {
  const [phase, setPhase] = useState<Phase>('splash');
  const [splashOut, setSplashOut] = useState(false);
  const [ringIn, setRingIn] = useState(false);
  const [editing, setEditing] = useState<CircleId | null>(null);
  const [filled, setFilled] = useState<Set<CircleId>>(new Set());
  const [welcomeIn, setWelcomeIn] = useState(false);
  const [data, setData] = useState<AppData>({
    you:    { name: '', tagline: '' },
    palace: { name: '', style: 'Classic' },
    butler: { name: 'Ace', tone: 'Sharp' },
  });

  function begin() {
    setSplashOut(true);
    setTimeout(() => {
      setPhase('ring');
      requestAnimationFrame(() => requestAnimationFrame(() => setRingIn(true)));
    }, 560);
  }

  function save(id: CircleId, d: Partial<AppData[CircleId]>) {
    setData(prev => ({ ...prev, [id]: { ...prev[id], ...d } as any }));
    const next = new Set([...filled, id]);
    setFilled(next);
    setEditing(null);
    if (next.size === 3) setTimeout(() => setPhase('complete'), 420);
  }

  function enter() {
    setPhase('welcome');
    requestAnimationFrame(() => requestAnimationFrame(() => setWelcomeIn(true)));
  }

  const hintText =
    filled.size === 0 ? 'Tap each circle to personalize' :
    filled.size === 3 ? 'Your palace awaits' :
    `${3 - filled.size} more to go`;

  return (
    <div class="join-root">

      {/* ── Splash ── */}
      {phase === 'splash' && (
        <div class={`splash${splashOut ? ' splash--out' : ''}`}>
          <div class="splash-bg" />
          <div class="splash-particles">
            {Array.from({ length: 11 }, (_, i) => (
              <span key={i} class="particle" style={`--i:${i}`} />
            ))}
          </div>
          <div class="splash-content">
            <div class="crest-wrap" style="width:52px;height:44px">
              {PALACE_CREST}
            </div>
            <h1 class="wordmark">Palace</h1>
            <svg class="flourish" viewBox="0 0 240 20" fill="none">
              <path d="M120 6l4 4-4 4-4-4z" fill="#C9A84C" />
              <path d="M112 10C96 10 88 2 64 2S32 10 20 10C14 10 8 7 8 5" stroke="#C9A84C" stroke-width="1" fill="none" stroke-linecap="round" />
              <path d="M128 10C144 10 152 2 176 2S208 10 220 10C226 10 232 7 232 5" stroke="#C9A84C" stroke-width="1" fill="none" stroke-linecap="round" />
            </svg>
            <p class="splash-sub">The home of those who live well</p>
            <button class="begin-btn" onClick={begin} type="button">Begin</button>
          </div>
        </div>
      )}

      {/* ── Ring / Complete ── */}
      {(phase === 'ring' || phase === 'complete') && (
        <div class={`ring-screen${ringIn ? ' ring-screen--in' : ''}${phase === 'complete' ? ' ring-screen--complete' : ''}`}>
          <p class="ring-hint">{hintText}</p>

          <div class="ring-container">
            {/* Connection lines */}
            <svg class="conn-svg" viewBox="0 0 360 340" fill="none" xmlns="http://www.w3.org/2000/svg">
              {([['you','palace'],['you','butler'],['palace','butler']] as [CircleId,CircleId][]).map(([a,b]) => {
                const active = filled.has(a) && filled.has(b);
                const [x1,y1] = CTR[a];
                const [x2,y2] = CTR[b];
                return (
                  <line
                    key={`${a}-${b}`}
                    x1={x1} y1={y1} x2={x2} y2={y2}
                    class={`conn-line${active ? ' conn-line--active' : ''}`}
                  />
                );
              })}
            </svg>

            {/* Circle nodes */}
            {(['you','palace','butler'] as CircleId[]).map(id => {
              const m = META[id];
              const isFilled = filled.has(id);
              const displayName =
                id === 'you'    ? data.you.name :
                id === 'palace' ? data.palace.name :
                                  data.butler.name;
              return (
                <button
                  key={id}
                  class={`circle-node circle-node--${id}${isFilled ? ' circle-node--filled' : ' circle-node--not-filled'}`}
                  style={`--color:${m.color};--glow:${m.glow};--delay:${m.delay}`}
                  onClick={() => setEditing(id)}
                  type="button"
                  aria-label={`Edit ${m.label}`}
                >
                  <div class="circle-body">
                    <span class="circle-icon">{isFilled ? <CheckCircle size={28} weight="duotone" /> : CIRCLE_ICON[id]}</span>
                    {isFilled && displayName && (
                      <span class="circle-display-name">{displayName}</span>
                    )}
                  </div>
                  <span class="circle-label">{m.label}</span>
                </button>
              );
            })}
          </div>

          <div class={`enter-zone${phase === 'complete' ? ' enter-zone--in' : ''}`}>
            <button class="enter-btn" type="button" onClick={enter}>
              Enter the Palace
            </button>
          </div>
        </div>
      )}

      {/* ── Welcome ── */}
      {phase === 'welcome' && (
        <div class={`welcome${welcomeIn ? ' welcome--in' : ''}`}>
          <div class="welcome-bg" />
          <div class="welcome-content">
            <div class="crest-wrap--big" style="width:64px;height:54px;color:#C9A84C">
              {PALACE_CREST}
            </div>
            <p class="welcome-label">Welcome to your Palace</p>
            {data.you.name && <h2 class="welcome-name">{data.you.name}</h2>}
            {data.palace.name && <p class="welcome-palace">{data.palace.name}</p>}
            <div class="welcome-pillars">
              {(['you','palace','butler'] as CircleId[]).map(id => {
                const m = META[id];
                const name =
                  id === 'you'    ? (data.you.name    || 'You')         :
                  id === 'palace' ? (data.palace.name || 'Your Palace') :
                                    (data.butler.name || 'Ace');
                return (
                  <div key={id} class="welcome-pillar" style={`--pc:${m.color}`}>
                    <span class="pillar-icon" style={`color:${m.color}`}>{CIRCLE_ICON[id]}</span>
                    <span class="pillar-label">{m.label}</span>
                    <span class="pillar-name">{name}</span>
                  </div>
                );
              })}
            </div>
            <a href="/home" class="enter-btn enter-btn--gold">
              <span>Enter Palace</span>
              <ArrowRight size={18} weight="bold" />
            </a>
          </div>
        </div>
      )}

      {/* ── Edit Sheet ── */}
      {editing && (
        <EditSheet
          id={editing}
          data={data}
          onSave={(d) => save(editing, d)}
          onDismiss={() => setEditing(null)}
        />
      )}

    </div>
  );
}

function EditSheet({ id, data, onSave, onDismiss }: {
  id: CircleId;
  data: AppData;
  onSave: (d: Partial<AppData[CircleId]>) => void;
  onDismiss: () => void;
}) {
  const [visible, setVisible] = useState(false);
  const m = META[id];

  useEffect(() => {
    requestAnimationFrame(() => requestAnimationFrame(() => setVisible(true)));
  }, []);

  function dismiss() {
    setVisible(false);
    setTimeout(onDismiss, 340);
  }

  function handleBackdropClick(e: MouseEvent) {
    if ((e.target as HTMLElement).classList.contains('sheet-backdrop--in')) dismiss();
  }

  return (
    <div
      class={`sheet-backdrop${visible ? ' sheet-backdrop--in' : ''}`}
      onClick={handleBackdropClick}
    >
      <div
        class={`sheet${visible ? ' sheet--in' : ' sheet--out'}`}
        style={`--color:${m.color}`}
      >
        <div class="sheet-handle" />
        <button class="sheet-close" onClick={dismiss} type="button" aria-label="Close">
          <X size={18} weight="bold" />
        </button>
        <div class="sheet-accent" />
        {id === 'you'    && <YouForm    data={data.you}    onSave={onSave} color={m.color} />}
        {id === 'palace' && <PalaceForm data={data.palace} onSave={onSave} color={m.color} />}
        {id === 'butler' && <ButlerForm data={data.butler} onSave={onSave} color={m.color} />}
      </div>
    </div>
  );
}

function YouForm({ data, onSave, color }: {
  data: AppData['you'];
  onSave: (d: Partial<AppData['you']>) => void;
  color: string;
}) {
  const [name, setName] = useState(data.name);
  const [tagline, setTagline] = useState(data.tagline);

  return (
    <div class="form-body">
      <div class="form-icon" style={`color:${color}`}>
        <User size={38} weight="duotone" />
      </div>
      <h2 class="form-title">Who are you?</h2>
      <p class="form-sub">Tell your palace about yourself</p>
      <div class="form-fields">
        <div class="field">
          <label class="field-label">Your name</label>
          <input
            class="field-input"
            type="text"
            placeholder="e.g. Junwon"
            value={name}
            onInput={(e) => setName((e.target as HTMLInputElement).value)}
            style={`--focus-color:${color}`}
            autocomplete="off"
          />
        </div>
        <div class="field">
          <label class="field-label">How do you live?</label>
          <input
            class="field-input"
            type="text"
            placeholder="Deliberately and with purpose"
            value={tagline}
            onInput={(e) => setTagline((e.target as HTMLInputElement).value)}
            style={`--focus-color:${color}`}
            autocomplete="off"
          />
        </div>
      </div>
      <button
        class="save-btn"
        style={`--color:${color}`}
        onClick={() => onSave({ name: name.trim(), tagline: tagline.trim() })}
        disabled={!name.trim()}
        type="button"
      >
        Save
      </button>
    </div>
  );
}

function PalaceForm({ data, onSave, color }: {
  data: AppData['palace'];
  onSave: (d: Partial<AppData['palace']>) => void;
  color: string;
}) {
  const [name, setName] = useState(data.name);
  const [style, setStyle] = useState<PalaceStyle>(data.style);

  const styleDesc: Record<PalaceStyle, string> = {
    Classic:  'Timeless, warm, and refined',
    Modern:   'Clean, minimal, and forward',
    Minimal:  'Pure, quiet, and essential',
  };

  return (
    <div class="form-body">
      <div class="form-icon" style={`color:${color}`}>
        <Buildings size={38} weight="duotone" />
      </div>
      <h2 class="form-title">Name your palace</h2>
      <p class="form-sub">Every palace deserves a name</p>
      <div class="form-fields">
        <div class="field">
          <label class="field-label">Palace name</label>
          <input
            class="field-input"
            type="text"
            placeholder="e.g. Park Palace"
            value={name}
            onInput={(e) => setName((e.target as HTMLInputElement).value)}
            style={`--focus-color:${color}`}
            autocomplete="off"
          />
        </div>
        <div class="field">
          <label class="field-label">Style</label>
          <div class="pill-group">
            {(['Classic', 'Modern', 'Minimal'] as PalaceStyle[]).map(s => (
              <button
                key={s}
                class={`pill${style === s ? ' pill--active' : ''}`}
                style={`--color:${color}`}
                onClick={() => setStyle(s)}
                type="button"
              >{s}</button>
            ))}
          </div>
          <p class="tone-desc">{styleDesc[style]}</p>
        </div>
      </div>
      <button
        class="save-btn"
        style={`--color:${color}`}
        onClick={() => onSave({ name: name.trim(), style })}
        disabled={!name.trim()}
        type="button"
      >
        Save
      </button>
    </div>
  );
}

function ButlerForm({ data, onSave, color }: {
  data: AppData['butler'];
  onSave: (d: Partial<AppData['butler']>) => void;
  color: string;
}) {
  const [name, setName] = useState(data.name);
  const [tone, setTone] = useState<ButlerTone>(data.tone);

  const toneDesc: Record<ButlerTone, string> = {
    Sharp:    'Direct, efficient, no filler',
    Friendly: 'Warm, conversational, encouraging',
    Formal:   'Polished, respectful, precise',
  };

  return (
    <div class="form-body">
      <div class="form-icon" style={`color:${color}`}>
        <Robot size={38} weight="duotone" />
      </div>
      <h2 class="form-title">Meet your butler</h2>
      <p class="form-sub">Your AI assistant, configured your way</p>
      <div class="form-fields">
        <div class="field">
          <label class="field-label">Butler name</label>
          <input
            class="field-input"
            type="text"
            value={name}
            onInput={(e) => setName((e.target as HTMLInputElement).value)}
            style={`--focus-color:${color}`}
            autocomplete="off"
          />
        </div>
        <div class="field">
          <label class="field-label">Tone</label>
          <div class="pill-group">
            {(['Sharp', 'Friendly', 'Formal'] as ButlerTone[]).map(t => (
              <button
                key={t}
                class={`pill${tone === t ? ' pill--active' : ''}`}
                style={`--color:${color}`}
                onClick={() => setTone(t)}
                type="button"
              >{t}</button>
            ))}
          </div>
          <p class="tone-desc">{toneDesc[tone]}</p>
        </div>
      </div>
      <button
        class="save-btn"
        style={`--color:${color}`}
        onClick={() => onSave({ name: name.trim(), tone })}
        disabled={!name.trim()}
        type="button"
      >
        Save
      </button>
    </div>
  );
}
