import React, { useCallback, useEffect, useState } from 'react';
import { api } from './api.js';
import { copyToast } from './toast.js';

// amerc Mansion — a hub of amerc services. First service: Showcase (reverse proxy).
export default function Mansion({ auth, setRoute }) {
  if (!auth.ready) return <div className="ap"><p>Loading…</p></div>;
  if (!auth.user) return (
    <div className="ap ap-gate"><h2>The Mansion</h2><p>Log in to use amerc services.</p><button className="px-action" onClick={() => setRoute('signin')}>Go to Login</button></div>
  );
  return (
    <div className="ap">
      <div className="ap-head"><h2>The Mansion</h2><span className="ap-by">{auth.user.handle}'s services</span></div>
      <p className="ap-hint" style={{ marginBottom: 18 }}>amerc hosts your services behind its edge. Each one lives in a room of the mansion.</p>
      <div className="mn-grid">
        <Showcase handle={auth.user.handle.toLowerCase().replace(/[^a-z0-9]/g, '')} />
        <div className="mn-soon"><div className="mn-soon-ico">🗄️</div><strong>Netdisk relay</strong><span>coming soon</span></div>
        <div className="mn-soon"><div className="mn-soon-ico">🤖</div><strong>Hosted webagent</strong><span>coming soon</span></div>
      </div>
    </div>
  );
}

function Showcase({ handle }) {
  const [list, setList] = useState([]);
  const [name, setName] = useState('');
  const [created, setCreated] = useState(null);
  const [err, setErr] = useState('');
  const load = useCallback(async () => { try { const d = await api('/showcase'); setList(d.showcases || []); } catch (e) { setErr(e.message); } }, []);
  useEffect(() => { load(); }, [load]);
  const register = async (e) => {
    e.preventDefault(); setErr('');
    try { const r = await api('/showcase', { method: 'POST', body: { name } }); setCreated(r); setName(''); load(); }
    catch (e2) { setErr(e2.message); }
  };
  const del = async (id) => { if (!window.confirm('Delete this showcase?')) return; try { await api(`/showcase/${id}`, { method: 'DELETE' }); load(); } catch (e2) { setErr(e2.message); } };
  const copy = (t) => copyToast(t);

  return (
    <div className="mn-card mn-card-wide">
      <div className="mn-card-head"><div className="mn-soon-ico">🌐</div><div><strong>Showcase</strong><span className="mn-tag">reverse proxy</span></div></div>
      <p className="ap-hint">Publish a web service from a local port to a public subdomain. Register a name, then in kebab's <b>delivery center (交付中心)</b> map your local port — requests to the public URL tunnel through your broker.</p>
      <form className="mn-reg" onSubmit={register}>
        <span className="mn-prefix">register</span>
        <input placeholder="show1" value={name} onChange={(e) => setName(e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, ''))} required />
        <span className="mn-suffix">.{handle}.amerc.ai</span>
        <button className="px-action px-auth-submit" type="submit">Register</button>
      </form>
      {err && <p className="px-auth-err">{err}</p>}
      {created && (
        <div className="mn-created">
          <p>✅ <b>{created.host}</b> reserved · DNS {created.dns}</p>
          <label className="ap-field">public URL<code className="ap-token" onClick={() => copy(created.url)}>{created.url} ⧉</code></label>
          <label className="ap-field">broker WS (kebab connects here)<code className="ap-token" onClick={() => copy(created.edgeWs)}>{created.edgeWs} ⧉</code></label>
          <label className="ap-field">edge token (bind {created.host})<code className="ap-token" onClick={() => copy(created.edgeToken)}>{created.edgeToken.slice(0, 28)}… ⧉</code></label>
          <p className="ap-hint">In the kebab delivery center: connect a broker to the WS with this token, send <code>{`{type:"bind",host:"${created.host}",port:<localPort>}`}</code>, and your local service is live at the public URL.</p>
        </div>
      )}
      <h4 className="ap-h4">My showcases</h4>
      {list.map((s) => (
        <div key={s.id} className="mn-row">
          <a href={`http://${s.host}/`} target="_blank" rel="noreferrer">{s.host}</a>
          <span>registered {new Date(s.created_at).toLocaleDateString()}</span>
          <button className="px-action" onClick={() => del(s.id)}>delete</button>
        </div>
      ))}
      {!list.length && <p className="ap-hint">No showcases yet — register one above.</p>}
    </div>
  );
}
