// Step 1: URL entry
const { useState } = React;

function Step1URL({ onLoaded }) {
  const [url, setUrl] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const handleSubmit = async (useUrl) => {
    const target = useUrl || url;
    if (!target) return;
    setError('');
    setLoading(true);
    try {
      const product = await window.SaltaireAgent.scrapeProduct(target);
      onLoaded(product);
    } catch (e) {
      setError(e.message);
      setLoading(false);
    }
  };

  return (
    <div className="step1-wrap fade-in">
      <div className="card step1-card">
        <div className="ornament eyebrow">Begin · Step One</div>
        <h2 className="serif">Paste a product URL</h2>
        <p className="sub">
          Drop in any Saltaire product page and our agent will read it, identify the piece,
          and build a heritage-faithful scene around it.
        </p>
        <div className="url-input-row">
          <input
            className="input"
            placeholder="https://www.saltairecompany.com/products/..."
            value={url}
            onChange={(e) => setUrl(e.target.value)}
            onKeyDown={(e) => e.key === 'Enter' && handleSubmit()}
            disabled={loading}
          />
          <button className="btn primary" onClick={() => handleSubmit()} disabled={loading || !url}>
            {loading ? <><span className="spinner" /> Reading</> : <>Analyze →</>}
          </button>
        </div>
        {error && <div style={{ color: 'var(--terracotta-deep)', fontSize: 13, marginBottom: 16 }}>{error}</div>}

        <div className="examples">
          <div className="examples-heading">
            <div className="hairline muted">Or choose an example</div>
            <div className="hairline faint">Pre-loaded</div>
          </div>
          <div className="example-list">
            {window.SaltaireData.examples.map((ex) => (
              <div key={ex.url} className="example-item" onClick={() => !loading && handleSubmit(ex.url)}>
                <div className="example-thumb" style={{ backgroundImage: `url(${ex.thumb})` }} />
                <div>
                  <div className="example-name">{ex.name}</div>
                  <div className="example-meta">{ex.meta}</div>
                </div>
                <div className="example-go">→</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

window.Step1URL = Step1URL;
