
import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom/client';
import { GoogleGenAI, Type } from "@google/genai";

// --- Types ---
type SchemaType = 'Article' | 'Product' | 'Organization' | 'LocalBusiness' | 'FAQPage' | 'Recipe';

interface SchemaField {
  name: string;
  label: string;
  type: 'text' | 'textarea' | 'number' | 'url' | 'date';
  placeholder?: string;
  required?: boolean;
}

interface SchemaDefinition {
  type: SchemaType;
  label: string;
  icon: string;
  description: string;
  fields: SchemaField[];
}

// --- Constants ---
const SCHEMA_DEFINITIONS: SchemaDefinition[] = [
  {
    type: 'Article',
    label: 'Article',
    icon: '📰',
    description: 'News, blog posts, or research articles.',
    fields: [
      { name: 'headline', label: 'Headline', type: 'text', required: true },
      { name: 'author', label: 'Author Name', type: 'text', required: true },
      { name: 'datePublished', label: 'Date Published', type: 'date', required: true },
      { name: 'image', label: 'Image URL', type: 'url' },
    ]
  },
  {
    type: 'Product',
    label: 'Product',
    icon: '📦',
    description: 'Products with prices and reviews.',
    fields: [
      { name: 'name', label: 'Product Name', type: 'text', required: true },
      { name: 'description', label: 'Description', type: 'textarea' },
      { name: 'brand', label: 'Brand', type: 'text' },
      { name: 'price', label: 'Price', type: 'number' },
      { name: 'currency', label: 'Currency (e.g. USD)', type: 'text' },
    ]
  },
  {
    type: 'FAQPage',
    label: 'FAQ Page',
    icon: '❓',
    description: 'Helpful for search result rich snippets.',
    fields: [
      { name: 'questions', label: 'Q&A Content', type: 'textarea', placeholder: 'Q: Is it organic? A: Yes.', required: true }
    ]
  },
  {
    type: 'LocalBusiness',
    label: 'Local Business',
    icon: '🏠',
    description: 'Physical locations and contact info.',
    fields: [
      { name: 'name', label: 'Business Name', type: 'text', required: true },
      { name: 'address', label: 'Street Address', type: 'text' },
      { name: 'phone', label: 'Phone', type: 'text' },
    ]
  },
  {
    type: 'Recipe',
    label: 'Recipe',
    icon: '🍳',
    description: 'Cooking steps and ingredients.',
    fields: [
      { name: 'name', label: 'Recipe Name', type: 'text', required: true },
      { name: 'prepTime', label: 'Prep Time (e.g. PT20M)', type: 'text' },
      { name: 'ingredients', label: 'Ingredients List', type: 'textarea' }
    ]
  }
];

// --- Application Logic ---
const App = () => {
  const [apiKeySet, setApiKeySet] = useState(false);
  const [selectedType, setSelectedType] = useState<SchemaType | null>(null);
  const [formData, setFormData] = useState<Record<string, string>>({});
  const [generatedCode, setGeneratedCode] = useState('');
  const [explanation, setExplanation] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [activeTab, setActiveTab] = useState<'form' | 'ai' | 'url'>('form');
  const [aiPrompt, setAiPrompt] = useState('');
  const [urlInput, setUrlInput] = useState('');

  useEffect(() => {
    const checkExistingKey = async () => {
      const aistudio = (window as any).aistudio;
      if (aistudio && await aistudio.hasSelectedApiKey()) {
        setApiKeySet(true);
      } else if (typeof process !== 'undefined' && process.env?.API_KEY) {
        setApiKeySet(true);
      }
    };
    checkExistingKey();
  }, []);

  const handleOpenKeySelector = async () => {
    const aistudio = (window as any).aistudio;
    if (aistudio) {
      await aistudio.openSelectKey();
      setApiKeySet(true);
    } else {
      alert("API key selector is not available. Please ensure window.aistudio is present.");
    }
  };

  const handleGenerate = async (mode: 'form' | 'ai' | 'url') => {
    setIsLoading(true);
    try {
      // Create fresh instance to use latest session key
      const ai = new GoogleGenAI({ apiKey: process.env.API_KEY });
      let resText = '';
      let insights = '';

      // Standardizing on 'gemini-3-flash-preview' for best reliability across tiers
      const MODEL_NAME = 'gemini-3-flash-preview';

      if (mode === 'form' && selectedType) {
        const response = await ai.models.generateContent({
          model: MODEL_NAME,
          contents: `Create valid JSON-LD schema for ${selectedType} using this data: ${JSON.stringify(formData)}. Return ONLY the JSON-LD code block inside <script type="application/ld+json"> tag.`,
        });
        resText = response.text || '';
      } else if (mode === 'ai') {
        const response = await ai.models.generateContent({
          model: MODEL_NAME,
          contents: `Analyze this content description and build the best JSON-LD schema.org markup: "${aiPrompt}". 
          Return a JSON object with:
          "schema": The full <script> block string.
          "type": The detected schema type (Article, Product, FAQPage, LocalBusiness, or Recipe).
          "explanation": Short reasoning for the choice.`,
          config: {
            responseMimeType: "application/json",
            responseSchema: {
              type: Type.OBJECT,
              properties: {
                schema: { type: Type.STRING },
                type: { type: Type.STRING },
                explanation: { type: Type.STRING }
              },
              required: ["schema", "type", "explanation"]
            }
          }
        });
        const parsed = JSON.parse(response.text || '{}');
        resText = parsed.schema;
        insights = parsed.explanation;
        if (parsed.type) setSelectedType(parsed.type as SchemaType);
      } else if (mode === 'url') {
        // Use non-JSON mode for grounding to ensure it works across all project setups
        const response = await ai.models.generateContent({
          model: MODEL_NAME,
          contents: `Scan this URL: ${urlInput}. Extract information and generate complete JSON-LD schema.org markup.
          Provide the output in this format:
          [SCHEMA]
          (script block)
          [TYPE]
          (type name)
          [EXPLANATION]
          (brief analysis)`,
          config: {
            tools: [{ googleSearch: {} }],
          }
        });
        
        const fullText = response.text || '';
        const schemaMatch = fullText.match(/\[SCHEMA\]\s*([\s\S]*?)\s*\[TYPE\]/);
        const typeMatch = fullText.match(/\[TYPE\]\s*([\s\S]*?)\s*\[EXPLANATION\]/);
        const explMatch = fullText.match(/\[EXPLANATION\]\s*([\s\S]*)/);

        resText = schemaMatch ? schemaMatch[1].trim() : fullText;
        insights = explMatch ? explMatch[1].trim() : '';
        const detectedType = typeMatch ? typeMatch[1].trim() : '';
        
        if (detectedType) {
          const matched = SCHEMA_DEFINITIONS.find(s => s.type.toLowerCase() === detectedType.toLowerCase());
          if (matched) setSelectedType(matched.type);
        }
      }

      setGeneratedCode(resText);
      setExplanation(insights);
    } catch (err: any) {
      console.error("Gemini API Error:", err);
      const msg = err.message || 'Unknown error';
      
      if (msg.includes("Requested entity was not found")) {
        setApiKeySet(false);
        alert("Session expired. Please re-select your API key.");
      } else if (msg.includes("billing")) {
        alert(`Billing Verification Failed: Even if billing is enabled, your project may be subject to regional restrictions or Tier 0 limits. Error: ${msg}`);
      } else {
        alert(`Request Failed: ${msg}. Try a different model or check your API Studio quotas.`);
      }
    } finally {
      setIsLoading(false);
    }
  };

  const handleCopy = () => {
    navigator.clipboard.writeText(generatedCode);
    alert("Schema copied!");
  };

  if (!apiKeySet) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-slate-50 p-6">
        <div className="max-w-md w-full bg-white rounded-3xl shadow-xl border border-slate-200 p-10 text-center">
          <div className="w-20 h-20 bg-indigo-600 rounded-[2rem] flex items-center justify-center text-white mx-auto mb-8 shadow-indigo-200 shadow-2xl">
            <svg className="w-10 h-10" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z" />
            </svg>
          </div>
          <h1 className="text-3xl font-black text-slate-900 mb-3 tracking-tight">Connect Gemini</h1>
          <p className="text-slate-500 mb-10 text-sm leading-relaxed">
            Please use the button below to select an API key. This ensures the app uses your specific project credentials securely.
          </p>
          <button 
            onClick={handleOpenKeySelector} 
            className="w-full bg-indigo-600 hover:bg-indigo-700 text-white font-black py-5 rounded-2xl shadow-xl transition-all"
          >
            Select API Key
          </button>
          <a 
            href="https://ai.google.dev/gemini-api/docs/billing" 
            target="_blank" 
            rel="noopener noreferrer" 
            className="block mt-6 text-xs font-bold text-indigo-600 hover:text-indigo-800"
          >
            View Google Cloud Billing Docs →
          </a>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen flex flex-col bg-slate-50">
      <header className="bg-white border-b border-slate-200 sticky top-0 z-50 px-6 h-16 flex items-center justify-between">
        <div className="flex items-center space-x-3">
          <div className="bg-indigo-600 p-2 rounded-lg text-white">
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4" />
            </svg>
          </div>
          <span className="font-black text-lg tracking-tight text-slate-900">
            Schema Architect
          </span>
        </div>
      </header>

      <main className="max-w-7xl mx-auto w-full p-6 lg:p-10 grid grid-cols-1 lg:grid-cols-12 gap-10 flex-1">
        <div className="lg:col-span-7 space-y-8">
          <section>
            <h2 className="text-[10px] font-black text-slate-400 uppercase tracking-[0.2em] mb-4">1. Select Target Type</h2>
            <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
              {SCHEMA_DEFINITIONS.map(s => (
                <button 
                  key={s.type} 
                  onClick={() => setSelectedType(s.type)} 
                  className={`p-5 rounded-3xl border-2 text-left transition-all duration-300 ${
                    selectedType === s.type 
                      ? 'border-indigo-600 bg-white shadow-xl translate-y-[-2px]' 
                      : 'border-transparent bg-slate-200/50 hover:bg-white hover:border-slate-300'
                  }`}
                >
                  <div className="text-3xl mb-2">{s.icon}</div>
                  <div className="font-black text-[11px] text-slate-800 uppercase tracking-tight">{s.label}</div>
                  <div className="text-[10px] text-slate-400 font-medium mt-1 line-clamp-1">{s.description}</div>
                </button>
              ))}
            </div>
          </section>

          <section className="bg-white rounded-[2.5rem] border border-slate-200 shadow-sm overflow-hidden">
            <div className="flex bg-slate-50/50 border-b border-slate-200">
              {(['form', 'ai', 'url'] as const).map(tab => (
                <button 
                  key={tab} 
                  onClick={() => setActiveTab(tab)} 
                  className={`flex-1 py-5 text-[10px] font-black uppercase tracking-[0.25em] transition-all ${
                    activeTab === tab 
                      ? 'text-indigo-600 bg-white border-b-2 border-indigo-600' 
                      : 'text-slate-400 hover:text-slate-600 hover:bg-slate-100/50'
                  }`}
                >
                  {tab === 'form' ? 'Manual' : tab === 'ai' ? 'AI Input' : 'URL Scan'}
                </button>
              ))}
            </div>
            <div className="p-10">
              {activeTab === 'form' && (
                selectedType ? (
                  <div className="space-y-6">
                    {SCHEMA_DEFINITIONS.find(s => s.type === selectedType)?.fields.map(f => (
                      <div key={f.name}>
                        <label className="block text-[10px] font-black text-slate-500 uppercase tracking-widest mb-2.5 px-1">{f.label}</label>
                        {f.type === 'textarea' ? (
                          <textarea 
                            className="w-full p-5 bg-slate-50 border border-slate-200 rounded-3xl text-sm h-32 focus:ring-4 focus:ring-indigo-50 focus:border-indigo-500 outline-none transition-all" 
                            value={formData[f.name] || ''} 
                            onChange={e => setFormData({...formData, [f.name]: e.target.value})} 
                            placeholder={f.placeholder} 
                          />
                        ) : (
                          <input 
                            type={f.type} 
                            className="w-full p-5 bg-slate-50 border border-slate-200 rounded-2xl text-sm focus:ring-4 focus:ring-indigo-50 focus:border-indigo-500 outline-none transition-all" 
                            value={formData[f.name] || ''} 
                            onChange={e => setFormData({...formData, [f.name]: e.target.value})} 
                            placeholder={f.placeholder} 
                          />
                        )}
                      </div>
                    ))}
                    <button 
                      onClick={() => handleGenerate('form')} 
                      disabled={isLoading} 
                      className="w-full bg-indigo-600 text-white py-5 rounded-[1.5rem] font-black shadow-2xl hover:bg-indigo-700 disabled:opacity-50 mt-4 transition-all"
                    >
                      {isLoading ? 'Processing...' : 'Generate Markup'}
                    </button>
                  </div>
                ) : <div className="py-24 text-center text-slate-400 font-bold uppercase tracking-widest text-[11px] opacity-40">Select a type above to use the manual form</div>
              )}
              {activeTab === 'ai' && (
                <div className="space-y-6">
                  <textarea 
                    className="w-full p-6 bg-slate-50 border border-slate-200 rounded-[2rem] text-sm h-64 focus:ring-4 focus:ring-indigo-50 focus:border-indigo-500 outline-none resize-none transition-all" 
                    placeholder="e.g. 'I run a local organic coffee shop called Java Bean in Portland. We are at 505 Burnside St...'" 
                    value={aiPrompt} 
                    onChange={e => setAiPrompt(e.target.value)} 
                  />
                  <button 
                    onClick={() => handleGenerate('ai')} 
                    disabled={isLoading || !aiPrompt.trim()} 
                    className="w-full bg-slate-900 text-white py-5 rounded-[1.5rem] font-black shadow-2xl hover:bg-slate-800 disabled:opacity-50 transition-all"
                  >
                    {isLoading ? 'Thinking...' : 'Analyze Content'}
                  </button>
                </div>
              )}
              {activeTab === 'url' && (
                <div className="space-y-6">
                  <input 
                    type="url" 
                    className="w-full p-6 bg-slate-50 border border-slate-200 rounded-[1.5rem] text-sm focus:ring-4 focus:ring-indigo-50 focus:border-indigo-500 outline-none transition-all" 
                    placeholder="https://example.com/page" 
                    value={urlInput} 
                    onChange={e => setUrlInput(e.target.value)} 
                  />
                  <button 
                    onClick={() => handleGenerate('url')} 
                    disabled={isLoading || !urlInput.trim()} 
                    className="w-full bg-violet-600 text-white py-5 rounded-[1.5rem] font-black shadow-2xl hover:bg-violet-700 disabled:opacity-50 transition-all"
                  >
                    {isLoading ? 'Scanning...' : 'Extract from URL'}
                  </button>
                </div>
              )}
            </div>
          </section>
        </div>

        <div className="lg:col-span-5 flex flex-col h-[calc(100vh-140px)] sticky top-24">
          <div className="bg-slate-950 rounded-[3rem] overflow-hidden flex flex-col flex-1 shadow-2xl border border-slate-800">
            <div className="px-8 py-5 bg-slate-900 flex justify-between items-center border-b border-slate-800">
              <span className="text-[10px] font-black text-slate-500 uppercase tracking-[0.25em]">JSON-LD Output</span>
              {generatedCode && (
                <button 
                  onClick={handleCopy} 
                  className="text-[10px] font-black text-white bg-indigo-600 hover:bg-indigo-500 px-5 py-2 rounded-full uppercase tracking-widest transition-all"
                >
                  Copy
                </button>
              )}
            </div>
            <div className="p-8 overflow-auto flex-1 font-mono text-xs text-indigo-300 leading-relaxed scrollbar-hide bg-slate-950">
              {generatedCode ? (
                <pre className="whitespace-pre-wrap">{generatedCode}</pre>
              ) : (
                <div className="h-full flex flex-col items-center justify-center text-slate-700 text-center select-none opacity-20">
                  <svg className="w-16 h-16 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1} d="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4" />
                  </svg>
                  <p className="font-black uppercase tracking-widest text-[10px]">Awaiting Generation</p>
                </div>
              )}
            </div>
            {explanation && (
              <div className="p-8 bg-indigo-950/20 border-t border-indigo-900/40 text-[11px] text-indigo-200/70 italic leading-relaxed">
                <span className="block not-italic font-black text-indigo-400 uppercase tracking-[0.2em] mb-2 text-[9px]">SEO Analysis</span>
                {explanation}
              </div>
            )}
          </div>
        </div>
      </main>
    </div>
  );
};

const root = ReactDOM.createRoot(document.getElementById('root')!);
root.render(<App />);
